estevan gomez estevan gomez - 4 months ago 6x
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:



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



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

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


$(function() {



function changeLayout(layout) {

if(layout == '4') {

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

} else

if(layout == '6') {

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



if(layout == '12') {

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






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


<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>

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?


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