Skip to content Skip to sidebar Skip to footer

Javascript Not Working In Script Tags?

I need to know why it's doing this because I'm using the javascript in the script tags on my site and it's not working. Why does my javascript not work in the script tags (switch w

Solution 1:

ok, so the reason why it doesn't work is that, at the time that the javascript first runs (and sets the on-click function on 'btn-toggle') there are no btn-toggle items in the page (because the page is still loading).

You need to run this stuff only after document.load

This happens by default in the jsfiddle which is why it works there. If you right-click and inspect on the jsfiddle page, you'll find it has converted your script to:

//<![CDATA[ 
window.onload=function(){
$('.btn-toggle').click(function() {
    $(this).find('.btn').toggleClass('active');  

    if ($(this).find('.btn-primary').size()>0) {
        $(this).find('.btn').toggleClass('btn-primary');
    }
    if ($(this).find('.btn-danger').size()>0) {
        $(this).find('.btn').toggleClass('btn-danger');
    }
    if ($(this).find('.btn-success').size()>0) {
        $(this).find('.btn').toggleClass('btn-success');
    }
    if ($(this).find('.btn-info').size()>0) {
        $(this).find('.btn').toggleClass('btn-info');
    }

    $(this).find('.btn').toggleClass('btn-default');

});

$('form').submit(function(){
    alert($(this["options"]).val());
    return false;
});
}//]]>  

which clearly works... so try that instead


Solution 2:

Your Javascript is running, but it is running before the DOM initializes, and as a result, the various JQuery selectors match no elements and the code appears to do nothing.

To fix this, either wrap your code in the ondomready event handler, or move all your javascript to the very bottom of the page so that the DOM is encountered before the scripts are executed.

To wrap your code in an ondomready event hander, do this:

$(function () {

// your code here

});

The above structure can appear anywhere on the page, even at the top as you have it, and jquery will automatically run it at the appropriate time.


Solution 3:

This is because your code is running before the DOM elements are initialised thus the code cannot find those elements on the page. Try enclosing your code in

$(document).ready(function(){
});

OR simply

$(function () {
});

Post a Comment for "Javascript Not Working In Script Tags?"