estevan gomez estevan gomez - 1 year ago 56
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download