0

I have a div that contains an image :

<div class="HD">
    <img class="image1"src="img/myimage.png">
</div>

the CSS applied to it is :

.HD img {
    position:absolute;
    top:570px;
    left:1120px;
    width:30px;
    height:90px;
    cursor:pointer
}

I want to apply a click function to the image inside the div. However, when I give an image id or class and use that to create the function the javascript does not fire. When the div does not have an image and I use the class the javascript works as expected. Below is the Javascript function :

$(".HD").click(function () {
    if($('.UpperDiv').attr('data-visible') == "hidden") {
        $('.UpperDiv').attr('data-visible', 'visible');
        $('.UpperDiv').animate({
            opacity:1
            // top:'250px'
        });
    } else {
        $('.UpperDiv').attr('data-visible','hidden');
        $('.UpperDiv').animate({
            opacity:0
            // top:'250px'
        });
    }
});

What could be the reason ? What is wrong with my code ?
How can I fire the javascript, when the user clicks on a div that contains an image?

For reference, this is the website I am trying to make, and the original working version.

3
  • Could you provide a jsFiddle? Commented Dec 2, 2013 at 3:35
  • I have not used jsfiddle .. I am trying to create one .. will that be useful if i did Commented Dec 2, 2013 at 4:12
  • Yes, definitely would be helpful for answering your question. Commented Dec 2, 2013 at 4:47

3 Answers 3

2

Can't you just use .toggle?

$(".HD").toggle(400);

Or .fadeToggle?

$(".HD").fadeToggle();
Sign up to request clarification or add additional context in comments.

1 Comment

I am sorry , I could not understand your answer ..why did you suggest the toggle .. will the toggle thing toggle between the 2 divs's.. but the current problem is that nothing happens on a click..
1

Try :

$(".HD").on({
    click : function(){
        if($('.UpperDiv').attr('data-visible')=="hidden")
        {
                $('.UpperDiv').attr('data-visible','visible');
                $('.UpperDiv').animate({
                        opacity:1
                        // top:'250px'
                });
        }else{
                $('.UpperDiv').attr('data-visible','hidden');
                $('.UpperDiv').animate({
                        opacity:0
                        // top:'250px'
                });
        }
    }
}, 'img');

2 Comments

Is there a way we could apply an image class or image id and on click of that fire the javascript .. Thank you for the answer though it does provide useful suggestions
Which version of jQuery are you using?
1
$(".HD > img").click(function () { });

Use this and try.

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.