0

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.

1
  • not sure why your alert isnt shown, but if you figure this one out, you have to set background-image to 'none' afaik to hide it. Commented Dec 13, 2011 at 9:39

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

So

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

will work

Comments

2

Try this code

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

Comments

2

Your javascript should be

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

Comments

1

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);
});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.