Deep Frozen
Deep Frozen

Reputation: 2075

div .click function not working

I am trying to call a DIV .click function, but it doesn't work. The div that I'm talking about is created with PHP.

This is the result from the PHP:

<div style="position:relative;width:700px;" id="colorcontainer">
<div class='color' style='background: url(kleuren/c121.jpg); background-size: 100 72; background-repeat:no-repeat;'><span class='txt'>CBM 121<br />Blank Gelakt Eiken</span></div>
</div>

Now I try to call the div .click function:

<script type="text/javascript">
$(document).ready(function(){
    $('#colorcontainer > div').click(function() {
        var name = this.css('background-image');
        alert(name);
    });
});

Now it does not show the alert at all. What am I doing wrong here? I've tried it without the document.ready, with .color and all sorts of stuff, but it just doesn't call the function.

Upvotes: 0

Views: 2260

Answers (6)

Romeo Besty
Romeo Besty

Reputation: 1

Its long ago the post has been answered. But just in case if someone come across something similar. No doubt the answer to the above question are perfectly stated but want to share few more tips to it.(if u don't have any syntax error - Try below methods to see if click event is firing or not) 1) just below the click event, write alert and see. this ensures that nothing before the click event is wrong. 2) look if the selector you mentioned exists. here $('.color') so there should be

Upvotes: 0

Mark Adesina Omoniyi
Mark Adesina Omoniyi

Reputation: 449

I think for performance purpose you should call the div that contained the background-image like below:

$('.color').click(function () {
     var name = $(this).css('background-image');
     alert(name);
});

Upvotes: 1

Alfabravo
Alfabravo

Reputation: 7589

Your javascript should be

$(document).ready(function(){
    $('#colorcontainer > div').click(function() {
        var name = $(this).css('background-image');
        alert(name);
    });
});

Upvotes: 2

Pavan
Pavan

Reputation: 4339

Try this code

$(document).ready(function(){ 
    $('#colorcontainer > div').click(function() { 
        var name = $(this).css('background-image'); 
        alert(name); 
    }); 
}); 

Upvotes: 2

dknaack
dknaack

Reputation: 60556

To ensure the use of jQuery. Use $(this) instead of this.

So

var name = $(this).css('background-image');

will work

Upvotes: 2

Prisoner
Prisoner

Reputation: 27628

You shouldn't use this, it should be $(this). Here is a working demo of your code.

Upvotes: 3

Related Questions