Ghozt
Ghozt

Reputation: 267

Using jquery to make a div clickable and to run a function

So i want to execute code when i click on a div.

So I have a function

function froth(){$("#area").load("test.html #enquiry1");}

I want to call this function when I click a div

 <div id="t1">Test</div>

So I try and use this code

 $('#t1').click(function(){
  froth();
  });

Nope it doesnt work.

BUT

I go to the HTML document and do this

<div id="t1" onclick="froth()">Test</div>

AND IT works perfectly.

So my question is, what am i doing wrong here? Why would it work when in the html doc and not work when i try and make it clickable with jquery?

Upvotes: 1

Views: 742

Answers (2)

jacktheripper
jacktheripper

Reputation: 14259

The main issue is that you need to bind your click event after the rest of the DOM has loaded

$(document).ready(function() {
    $('#t1').on('click', function(){
        froth();
    });
});

You can see a live example here

Upvotes: 5

PSR
PSR

Reputation: 40358

$(document).on('click', '#t1', function() { 
 froth();
});

Upvotes: 1

Related Questions