Jimmi
Jimmi

Reputation: 35

Where do I put this JS code to make it work?

I essentially recreated the table section of what I needed to make JS for and put together some working code in JS fiddle, but when I try to add it to where the table section is or within any other functions that are called int he html it seems to break the page... any idea where to put this? http://jsfiddle.net/UyHj3/13/

$("tr.clickable.subheading td").click(function() {
    $(this).parents("tr.clickable.subheading").nextUntil("tr.clickable.subheading").toggle();
});​​

Upvotes: 0

Views: 111

Answers (5)

codef0rmer
codef0rmer

Reputation: 10530

Put in either

$(document).ready(function () {
   // I execute your code when the DOM is ready. 
});

Or

$(window).load(function () {
  // I execute your code when the entire page is loaded (including images or iframes)
});

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Your problem is that you're trying to attach an event handler to an element that doesn't exist in the DOM. in jsFiddle, by default the code runs after onload meaning the DOM + images are fully loaded.

Wrap the code in the DOM ready event:

$(function() {
    $("tr.clickable.subheading td").click(function() {
        $(this).parents("tr.clickable.subheading").nextUntil("tr.clickable.subheading").toggle();
    });
});

Updated Fiddle

or put the code in the end of the <body> tag, like with this Fiddle.
But the first option is considered to be a better practice.

ready event docs:

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

Upvotes: 3

DorkRawk
DorkRawk

Reputation: 770

Looks like you have some jQuery there, so make sure that you are including a reference to the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

And put your code inside the $(document).ready(){}:

$(document).ready(function(){
// your code
};

Upvotes: 1

tzerb
tzerb

Reputation: 1433

There should be a JavaScript pane. Make sure you're using JQuery on the left hand menu.

Upvotes: 0

Colleen
Colleen

Reputation: 25489

You always want to put event handlers inside a document.ready function, like

$(document).ready(function(){

//your code

});

Your updated fiddle: http://jsfiddle.net/ccross59/UyHj3/15/

Upvotes: 2

Related Questions