0

I have an element that isn't clickable at first, but I'd like to make clicking on another div make it clickable.

What I did was

$("#div_1").addClass("selected");

$(".selected").click(function() {
    $("#block").animate({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500);
});​

but this doesn't seem to work, I'm not sure what's wrong with this, maybe there's a better way to do this?

2
  • Well it depends upon where you're firing the event from, and where you're binding the click event. Please post some more javascript code. Commented Oct 24, 2012 at 16:32
  • works fine here..jsfiddle.net/hVvJK/1.. You just have to make sure you are binding the click event handler after the element exists.. Or you can use delegation Commented Oct 24, 2012 at 16:36

2 Answers 2

1
Try something like this:

$("#div_1").addClass("selected");

$("#div_1").click(function() {
    if($(this).hasClass('.selected') {
    $("#block").animate({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500);
    }
});​

Also for usability purposes when you add the click-able functionality use this to make it appear click-able to the user:

$("#div_1").addClass("selected").css('cursor', 'pointer');
Sign up to request clarification or add additional context in comments.

Comments

0

You need to delegate such cases... try using .on() and attach the event to the static parent..

Because when the class is added the event is already associated to when the DOM loads.. So delegating it will solve the problem.

$("#div_1").addClass("selected");

$('body').on("click", ".selected", function() {
     // Your code here
});​

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.