tags:

views:

381

answers:

6
<div id="pic">
  <div id="left">
    <img src="images/left.png" />
  </div>
  <div id="right">
   <img src="images/right.png" />
  </div>
</div>

I want to hide the div with id "right" when I click on the div with id "left"

Code I am using:

$("#left").click(function(){$("#right").hide();});

This is not working, what is the reason? And how will I achieve what I intend to?

A: 

Your code seems to be fine, but looks like you are missing the jQuery's ready event, try this:

$(function(){
 $("#left").click(function(){
   $("#right").hide();
  });
});

Note: $(function(){ is short form of ready event code.

Sarfraz
no thats not working.. thanks
srk
@srk: are your divs dynamically generated?
Sarfraz
+2  A: 

Your code is correct and works for me.

Something else is wrong.

Try setting up the handler in document.ready

$(document).ready(function() {

  $("#left").click(function() { $("#right").hide(); });


});
Sky Sanders
A: 

Some possibilities:

  1. did include the jquery.js file in the html head
  2. are there no bugs in the preceding javascript before that jquery line? They could stop execution before reaching that point.
  3. are the id's unique? Maybe you have multiple elements with id='right'?
catchmeifyoutry
+1  A: 

The click event can only be added after the #left div has loaded. For this reason wrap your existing jquery in a domready call.

$(document).ready(function(){
     $("#left").click(function(){$("#right").hide();});
});
sammcd
+2  A: 

There are one of three things wrong, since your code is technically correct:

  1. Your click function does not appear in your $(document).ready function
  2. Your page repeats ids. Use classes instead.
  3. Your divs are created dynamically and therefore not bound on $(document).ready

(1) is a simple fix. Just put in your $(document).ready. (2) just change your id attributes to classes, but if you want to make sure that you hide the correct div you may need to do some traversing. (3) can be fixed by using $(selector).bind('click', function(){}); or $(selector).live('click', function(){});

Good luck

Jason
A: 

Thanks guys.. as jason said... its that the divs are created dynamically.. got it working now...

srk
if you've got it working you should mark the correct answer what did it for you or post your solution here and mark is as correct answer.
Zaagmans