estevan gomez estevan gomez - 5 months ago 11
jQuery Question

jQuery function only working once when jquery .load is used

I am using jquery .load() function to load external .html files into my index.html page.

Here is my index.html:

index.html

<!doctype>
<html>
<head>

<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

<div id="nav"></div>





<script src="jquery/jquery.min.js"></script>


<script>


$(function() {

$("#nav").load("nav.html");

});



function changeLayout(layout) {

if(layout == '4') {

$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-4");



} else

if(layout == '6') {

$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");



}

else

if(layout == '12') {

$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-12");



}

}


</script>




</div>

</body>
</html>


This is the nav.html file that I'm loading:

nav.html

<div id="subnav" class="container">
<div class="row">
<div class="btn-wrapper">
<div class="layout">
<button onclick="changeLayout('4');">Layout1</button>
<button onclick="changeLayout('6');">Layout1</button>
<button onclick="changeLayout('12');">Layout1</button>
</div>
</div>
</div>
</div>


My problem is that the changeLayout function above will only work 'Once' and then I would need to reload the whole page to get it to work again.

Why is this happening and how can I fix this problem?

Answer

You need to add type="button" to your buttons currently your buttons seem to be submitting the page.

Also no need for href attribute in buttons.

<button type="button" onclick="changeLayout('4');">Layout1</button>
<button type="button" onclick="changeLayout('6');">Layout1</button>
<button type="button" onclick="changeLayout('12');">Layout1</button>

Move you changelayout function to nav.html