Thomas Ravnholt
Thomas Ravnholt

Reputation: 13

Load image button, jquery doesn't work

I have never used jquery before, so i might just have forgotten something. what i want to do is add a button on my page that loads some images when pressed. or even make it load a div that i have created already.

In my head tag i have this.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  $("button").click(function () {
    var imgUrl = $(this).data('rel');
    $("#area").html("<img src='" + imgUrl + "' alt='description' />");
  });
</script>

and in my body i have the button.

<button data-rel="img/inasecond.jpg">Click Me</button>

please help my out here, im going to study a little jquery later when i got the time, but right now i just need to learn how to use code found on the web.

Upvotes: 0

Views: 436

Answers (4)

Laxmikant Dange
Laxmikant Dange

Reputation: 7698

Adding script is easy in html, but look before what those scripts uses, if your script uses any dom elements then that script block should execute after that dom element. like if you write an click event handler before body and button is in body then the handler will not attach to that button. In jQuery there is $(document).ready() method which takes a callback function which will get executed when your document gets loaded.

so here you have two options one is to use

$(document).ready(function(){
//Your code here
})

or another option is move your script block at the end of body tag so when your script block will get executed, till all dom elements will already loaded

Upvotes: 0

Amit Singh
Amit Singh

Reputation: 2275

Your code works fine. All you need to do is wrap it in $(document).ready()

So it should look like :

$(document).ready(function(){
$("button").click(function () {
    var imgUrl = $(this).data('rel');
    $("#area").html("<img src='" + imgUrl + "' alt='description' />");
  });
});

Here is the DEMO

Upvotes: 0

Kiran
Kiran

Reputation: 121

<script>
 $(document).ready(){ 
 $("button").click(function () {
    var imgUrl = $(this).data('rel');
    $("#area").html("<img src='" + imgUrl + "' alt='description' />");
  });
});
</script>

Upvotes: 0

Philip G
Philip G

Reputation: 4104

jQuery cant run before the document is fully loaded. Hence:

Wrap your jQuery code inside

$(document).ready(){ //your jQuery here });

Then it should work ;)

Upvotes: 1

Related Questions