user2468409 user2468409 - 5 months ago 24
HTML Question

Load first page onload and first nav button clicked onload

First hello to all. I am relatively new to jquery and on a learning curve.

My script is this:



<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js">
</script>

<script>
$(function () {
$('#content').find('#nav a').on('click', function (e) {
e.preventDefault();
var page = $(this).attr('href');
$('#content2').load(page);
});
});
$(function() >{
$('#content').find('#nav a').click(function() {
$('#nav a').removeClass('selected');
$(this).addClass('selected');
});
});
</script

<div id="content">
<embed type="image/svg+xml" src="x.svg" />
<div id="svgfix">
<embed type="image/svg+xml" src="1.svg" />
<embed type="image/svg+xml" src="2.svg" />
<embed type="image/svg+xml" src="3.svg" />
<embed type="image/svg+xml" src="4.svg" />
<embed type="image/svg+xml" src="5.svg" />
<embed type="image/svg+xml" src="6.svg" />
</div>
<div id="nav">
<a href="1.htm"><img type="image/svg+xml" src="1.svg" /></a>
<a href="2.htm"><img type="image/svg+xml" src="2.svg" /></a>
<a href="3.htm"><img type="image/svg+xml" src="3.svg" /></a>
<a href="4.htm"><img type="image/svg+xml" src="4.svg" /></a>
<a href="5.htm"><img type="image/svg+xml" src="5.svg" /></a>
<a href="6.htm"><img type="image/svg+xml" src="6.svg" /></a>
</div>
</div>
<div id="content2"><h1></h1></div>





The script works well. The only problem i have, i want the first page to auto load and the first button to be on selected. I have tried to find a solution here and read trough the topics, but nothing has worked so fare.

The script should load on click trough the nav bar with the 6 pages and it does and each button will be selected. But i would like on first page load, to auto select the first button and autoload the first page.

I hope my question is understandable and thanks for your time and help in advance...

Answer

You can do something like this:

Create a function and call when the page is ready and on click event

$(function () {

function getPage(el){
var page = $(el).attr('href');
$('#content2').load(page);
$('#nav a').removeClass('selected');
$(el).addClass('selected'); 
}


 getPage($('#nav a:first-child'));//get the first page
$('#nav a').on('click', function (e) {
e.preventDefault();
     getPage($(this));            
});
});