tags:

views:

51

answers:

6

I have assigned a onClick event to textbox. When I am clicking on textbox, I want to execute the click event of div also. How to do that in Javascript?. The div and textbox are not nested they are on different position in document.And thanks in advance for the Help.

A: 

I would recommend using a function that is called by both.

Camilo Martin
It is ok. But I want to execute div click event when I will click on textbox
Pranjali
That's my point; using a function that has the code that's the same between both, and make both OnClick events reference it. Differences in code can be appended to the individual OnClicks.
Camilo Martin
A: 

I am reading it as if you have 2 different functions. We'll just say textbox(); and div();

your onclick for the textbox should read

onclick="textbox(); div();"

That should call both functions on the same event, where with the div you can put only the div() function or both like the example above. Just seperate the function calls with a semi-colon.

jon
-1 failure to exploit bubbling as appropriate
annakata
I think this will also work. Thanks.
Pranjali
"The div and textbox are not nested, they are on different position in document."
jon
No problem Pranjali
jon
A: 

You need to know even bubbling in order to do that.

Sarfraz
A: 

I recommend reading PPK's blog post about events. It's a bit old, but it weathers the test of time well. See:

http://www.quirksmode.org/js/events%5Forder.html

jeremyosborne
A: 

If the elements are nested the event will bubble up (if you aren't cancelling it) so:

<div onclick="foo()">
    <input type="text" onclick="bar()" />
  </div>

Will result in a call to bar then foo. This is a bit of a kludge though since you don't really want to have inline event binding if you can help it. This is one of those cases where use jquery might be appropriate since $('#mydiv, #myinput').click(baz) is quite clean.

annakata
The textbox and div are not nested. They are in different places.
Pranjali
A: 

Try this:

 function twoActions(){
  var textboxId = document.getElementById("textboxId");

  var divId = document.getElementById("divId");

   textboxId.style.border = "red"; // action one  

   divId.style.border = "red";  // action two

}

you tie this function to the textbox - onClick it will change the border color of the text box and that of the Div.

Q_the_dreadlocked_ninja
thanks. I will try this function to solve my problem
Pranjali