Jump to content
sfanett

inkluder HTML

Recommended Posts

Hei jeg lurte på hvordan kode man skal bruke for inkludere eks i HTML side ikke i PHP

sånn er det med PHP:  <?php include("templates/theme/meny_include/top_left.html"); ?>

Share this post


Link to post

Hei, dette kan du gjøre uten PHP, men ikke i ren HTML.

Her er en metode du kan bruke for å inkludere HTML uten server side kode, med JavaScript.

Filstruktur:

  • index.html
  • 1.html
  • 2.html
  • 3.html

 

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <ul>
    <li><a href="#" class="content-link" data-href="1.html">1</a></li>
    <li><a href="#" class="content-link" data-href="2.html">2</a></li>
    <li><a href="#" class="content-link" data-href="3.html">3</a></li>
  </ul>
  <div id="content"></div>


  <script>

    const contentLink = document.querySelectorAll(".content-link")
    const contentElem = document.getElementById("content")


    contentLink.forEach(link => {
      link.addEventListener("click", event => 
      {
        event.preventDefault();
        requestFile(link.dataset.href)
      })
    })


const requestFile = theFile =>
{
  const oReq = new XMLHttpRequest()
  oReq.addEventListener("load", handleRequest)
  oReq.open("GET", theFile)
  oReq.send()
}

const handleRequest = body => 
{
  contentElem.innerHTML = body.target.response
}

  </script>
</body>
</html>

 

Edited by Dan-Levi

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...