My JavaScript isn't working

Hey everyone, I’m having a play about with some JavaScript and cant seem to get this code working locally. It’s something from fiddle, but when putting into a local folder, it no longer works. Here is my code:

    <!DOCTYPE html>
<html>
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
	<script src="js/input.js" type="text/javascript"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	<title>Test</title>
</head>
<body>
	<form>
	    <input type="checkbox" value="1">1<br />
	    <input type="checkbox" value="2">2<br /> 
	    <input type="checkbox" value="3">3<br />
	</form>

	<div id="Output">
	    
	</div>
</body>
</html>

And the JavaScript located in js/input.js:

  $('input').click(function(){
    if($(this).is(":checked")) {
        $('#Output').text($('#Output').text() + $(this).val());
    } else {
    }
});

Any guidance on how to get this working locally would be much appreciated

Try moving your scripts before the </body> or wrapping your input.js with $(function(){...}).

What’s happening is that you are binding the click event to elements that haven’t been created yet (the DOM is loaded from top to bottom).

The other technique is to place your jQuery code inside of a load handler, such as this:

$(function () {
    // jQuery code in here
});

but other than that, @labofoz is dead right - move your script tags down to just before the tag for best compatibility.

1 Like

99.99%+ of JavaScript works best when attached to the bottom of the page.

The only two exceptions I have come across are framebreaker scripts and scripts such as Modernizr that add classes to the <html> tag so that the page can be styled based on what JavaScript the browser supports.

1 Like

Another thing to consider: Are you accessing this via “file:\\\C:\path\to\document\index.html” or “http://localhost/document/index.html”? A lot of times I’ve tried testing JavaScript not realising that I’m using the “file:” protocol instead of the “http:” protocol. It can make a difference (although not always.)

HTH,

:slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.