pacel
September 14, 2018, 8:54am
1
I’d like to create a multi-page web template, so I’ve started with a blank Foundation starter template, and have the nav bar at the top with 3 hyperlinks in it, Link1, Link2, Link3. I’d like to know how to make an HTML snippet load in a DIV with ID=mysnippet when each link is clicked. The snippets are named snippet1, snippet2 and snippet3.
Probably very easy but never have tried this before, so I’m hoping to see an example.
thanks!
Rod
September 15, 2018, 6:23am
2
Download Example
I have used the Bootstrap framework to help with formatting.
The html code is as follow:
<nav class="navbar navbar-expand-sm bg-light">
<ul class="navbar-nav">
<li id="link1" class="nav-item"><a class="nav-link" href="#">Link 1</a></li>
<li id="link2" class="nav-item"><a class="nav-link" href="#">Link 2</a></li>
<li id="link3" class="nav-item"><a class="nav-link" href="#">Link 3</a></li>
</ul>
</nav>
<div id="mysnippet" class="container-fluid">
result goes here
</div>
The below script, which uses jQuery for simplicity, gets the css id of the link that has been clicked and based to load the correct snippet:
$(document).ready(function(){
$("li").click(function(){
var clicked= $(this).attr('id');
var thisSnippet ="";
switch(clicked){
case 'link1':
thisSnippet = 'Snippet1.html';
break;
case 'link2':
thisSnippet = 'Snippet2.html';
break;
case 'link3':
thisSnippet = 'Snippet3.html';
break;
}
$("#mysnippet").load("Snippets/" + thisSnippet);
});
});
Make sure to "include" the scripts highlighted in orange in your web section.
Rod
September 15, 2018, 1:06pm
3
Download Example version 2
Even better, if you assign to every link the name of its corresponding snippet as css id selector, the script can also be simplified:
HTML Code
<nav class="navbar navbar-expand-sm bg-light">
<ul class="navbar-nav">
<li id="Snippet1" class="nav-item"><a class="nav-link" href="#">Link 1</a></li>
<li id="Snippet2" class="nav-item"><a class="nav-link" href="#">Link 2</a></li>
<li id="Snippet3" class="nav-item"><a class="nav-link" href="#">Link 3</a></li>
</ul>
</nav>
<div id="mysnippet" class="container-fluid">
result goes here
</div>
JavaScript
$(document).ready(function(){
$("li").click(function(){
$("#mysnippet").load("Snippets/" + $(this).attr('id') + ".html");
});
});
pacel
September 17, 2018, 8:38am
4
excellent, thank you Rod, I will give this a try.
Hi there
I’m having an issue with this solution where the snippet doesn’t load. I get an error where the snippet can’t be found.
any idea why ?