mouse event problem with nested elements - javascript

I have something similar to the following:
<div onclick="divClickEvent();">
<img onmousedown="imgOnDownEvent();" />
</div>
The problem is that if you mouse down on the img, the div click fires on mouse up. I tried to override the div onclick by adding an onclick="return false;" to the img element, but the div onclick is still firing. I also have a cancel bubble and return false in a document onmouseup event (which gets attached dynamically in the img ondown event).
I've run out of ideas. Why is the div still processing the event, and how do I stop it?

cancelBubble is Deprecated.
Use event.stopPropagation() instead of cancelBubble [non-standard method] in the onclick event of the image.
which prevents further propagation of the current event.

Consider using an abstraction framework like jQuery, where you can stop propagation with the same method regardless of the browser version:
<div id="image_holder">
<img id="some_image" alt="" src="" />
</div>
<script type="text/javascript">
$(document).ready(function(){ // This will be run when DOM is ready
var holder = $('#image_holder'),
someImage = $('#some_image');
someImage.bind('mousedown', function(event){
// This will be run on mousedown
event.preventDefault().stopPropagation();
});
});
</script>

Related

Use javascript to auto click a picture when user moves mouse pointer over the picture

my idea is a script that auto click the picture when user moves mouse pointer over the picture. Please guide me how to make it. Thank you in advanced.
Not that I support such a thing. but...
el = document.getElementById('lol');
el.onmouseover = function(){el.click();}
el.onclick = function(){
//your code for having clicked the element
}
Here is a jsfiddle: http://jsfiddle.net/Rap6M/
But!, why not just put your code in the onmouseover listener? Especially seeing that (though widely acceptable) not all browsers suppoer the el.click()
Here is what MDN has to say about click(): https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.click
Noting that they say:
However, bubbling of a click event will not cause an <a> element to
initiate navigation as if a real mouse-click had been received.
It sounds like you want to trigger a DOM mouse onclick event but during mouse overs on certain elements (in this case a picture).
My suggestion would be to just trigger the event (mouse onclick) whenever you hover over the image. Just have an event listener on your object listening for a onmouseover event, once you detect it, fire off a click event on whatever element you need to.
Take a look at this:
<img id="my_image" src="myimage.png"></img>
<div id="my_clicky_div">My click event will be triggered</div>
<script type="text/javascript">
$("#my_clicky_div").on("click", function() {
console.log("My click event has been triggered!")
})
$("#my_image").on("mouseover", function() {
$("#my_clicky_div").trigger('click');
});
</script>
You create an image tag and a div. Whenever you hover (mouseover) this image, the div's onclick event is triggered.
To make it easier, you should just bind whatever event you need triggered onto the onmouseover event, you essentially bypass a step as so:
<img id="my_image" src="myimage.png"></img>
<script type="text/javascript">
$("#my_image").on("mouseover", function() {
// Instead of issuing another event, run the code that happens during the click event
});
</script>
Let me know if this helps!
References:
http://api.jquery.com/mouseover/, http://api.jquery.com/trigger/, http://api.jquery.com/on

Event is firing Two times

Hi I am binding onclick event to parent as well as child (same method). Event is getting fired two times How to avoid this?
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId" onclick="javascript:somemethod()"></button>
</div>
Onclick of Div the event is getting fired two times.
Try:
<button id="childId" onclick="javascript:somemethod(event)"></button>
JS code
function somemethod(event){
event.stopPropagation();
}
The reason that the onclick event is showing twice, is because there is something called event bubbling in JavaScript.
Take a look at the following:
This image shows that, if the <img> was clicked, the event would "bubble" up to the <p> tag, then to the <div>, then to the rest of the document. If there was an onclick event on the <p> tag, and even if the <p> tag was not clicked (but the <img> was), the event would necessarily "bubble" all the way up the DOM, and would still continue when an event was fired on the <p> tag (in other words, if you also had an onclick event on the <div>, then that would fire as well.
So what you should do is this:
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId"></button>
</div>
In other words, as I explained above, you wouldn't need the extra onclick event handler in your button anymore, because when your button is clicked, the event bubbles up to the parent div, which would fire that event.
If you want to use your original HTML code, that's fine as well - just add this:
function somemethod(evt) { // the method you run
// some code
evt.stopPropagation(); // stops bubbling
}
This effectively stops the event from bubbling up your DOM tree.
It is getting called twice because you are calling it twice, i.e. once in the div click and once in the button click. the button is already inside the div.
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId" onclick="javascript:somemethod()"></button>
</div>
try
<div id="sparentId">
<button id="childId" onclick="javascript:somemethod()">Click Me</button>
</div>
use
event.stopImmediatePropagation()

button click event triggering wrong event handler

I have a div display some titles of music which is clickable. When you click it it will show some more detail information. Then I also have a button in the clickable div. When I click the button. It won't call the function of the button but the function of the div? Is there a way to solve this? Thank you!
$("#myComList").append("<div id="+comListID+" class=listDiv> <p class=comTitle><? echo $row["compositionTitle"] ?>(<?echo $row["year"]?>)</p><button id="+comListID+"btn class=addNewArrBtn>Add new Arrangement</button> <p class=comOri>BY <? echo $row["OrigComposer"] ?></p> </div>");
$('#'+comListID).click(function() {
$(this).find("li").slideToggle('slow', function() {
});
$("#"+comListID+"btn").click(function(){
addNewArr(comListID);
});
It's called 'bubbling'. The button is inside the div so it's executing button then up the chain to div. Add event.stopPropagation() inside the button function.
$("#"+comListID+"btn").click(function(event){
event.stopPropagation();
addNewArr(comListID);
});
From jQuery documentation:
By default, most events bubble up from the original event target to
the document element. At each element along the way,
jQuery calls any matching event handlers that have been attached.
A handler can prevent the event from bubbling further up the document
tree (and thus prevent handlers on those elements from running) by
calling event.stopPropagation(). Any other handlers attached on the
current element will run however. To prevent that, call
event.stopImmediatePropagation(). (Event handlers bound to an element
are called in the same order that they were bound.)
http://api.jquery.com/on/
So you'd call event.stopPropagation() inside the button click handler, as to stop the div event from firing.
I believe I understand your question without seeing the code. The problem it sounds like stems from the click event bubbling or propagating up. Below is a sample of code to try and a link to a fiddle for you to test:
<div id="testDiv" onclick="alert('Stop Clicking Me!');">
<button type="button" onclick="function(e) { alert('You hit the button!'); e.stopPropagation(); }">Click Me!</button>
</div>
In this function, the:
e.stopPropagation();
prevents the click event from filtering up to its parent container (in this case "testDiv") and triggering its click event as well. You can test it and see for yourself in the jsfiddle below:
Test Fiddle
EDIT:
In your case:
$("#"+comListID+"btn").click(function(e){
addNewArr(comListID);
e.stopPropagation();
});
add the event parameter to the click function and stop it from propagating to the parent.
Hope this helps.

Prevent javascript onclick on child element

Ok, simple question:
<div onclick="javascript:manualToggle(this)">
<span>Allowed to click</span>
<span>Not allowed to click</span>
<span>Allowed to click</span>
</div>
Without replicating the manualToggle on to the 2 spans that are allowed to click, how can I prevent the "Not allowed to click" span from firing it's parent div onclick event when it is clicked on?
Give the span an id an attach onclick event to it and use
A jQuery sample
$("#spn2").click(function(event){
event.stopPropagation();
});
event.stopPropagation(): Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
It would make sense to use a library but without you can try this (edited with an entire page to test):
<html><head></head>
<body>
<script type="text/javascript"><!--
function manualToggle(val)
{
alert(val.id);
}
--></script>
<div id="test" onclick="manualToggle(this);">
<span>Allowed to click</span>
<span onclick="event.cancelBubble=true;if (event.stopPropagation) event.stopPropagation();">Not allowed to click</span>
<span>Allowed to click</span>
</div>
</body>
</html>
You need an event handler (it's very easy to do this in something like jQuery) that catches clicks for the spans within the div and only fires the function if, for example, the span has/hasn't a particular class.
I just had the same issue and could not get jQuery to work so I used simple Javascript:
document.getElementById("your_span").addEventListener("click", (event) => {
event.stopPropagation();
});
That did the trick for me. Obviously you need to add the addEventListener to every Element you wanna apply this to. Since I do a lot of DOM manipulation this was not an issue for me.
Hope this helps anyone :)
with mootools you can use the method stopPropagation:
$('myChild').addEvent('click', function(ev){
ev.stopPropagation(); // this will prevent the event to bubble up, and fire the parent's click event.
});
see http://mootools.net/docs/core/Native/Event#Event:stopPropagation
also see this very similar question: How can I stop an onclick event from firing for parent element when child is clicked?
Possible solution: give the span's id's and check whether the clicked id is allowed to be clicked in your function
bad idea: you don't know which span is clicked since you call the function from your div...
<div onclick="manualToggle(this)">
<span>Allowed to click</span>
<span>Not allowed to click</span>
<span>Allowed to click</span>
</div>
<script>
function manualToggle(cur){
if(cur !== event.target) return false;
//CODE
}
</script>
Here we have set a click event on div tag,
and we are passing the current element(div) as parameter
inside the manualToggle function you have the element in params where you have set the event,
inside the function we have event (a global var object), where you can get the clicked element (event.target),
if the clicked element is not same(equal) to the element where we have set the event then do nothing.
there are some other methods are also available, use stopPropagation
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Why does this Prototype code work like this?

This is my html:
(note: I didn't use a background image on the a just for simplicity to show someone how this could work)
<div class="foo">
<ul>
<li><img src="bar.gif" /></li>
<li><img src="baz.gif" /></li>
</ul>
</div>
And my JavaScript:
<script type="text/javascript">
Event.observe(window, 'load', function() {
$$('.foo a').each(function(a) {
alert(a); // this is the anchor
a.observe('click', fooClick);
});
function fooClick(event) {
alert(event.element()); // this is the img
}
</script>
Why is the element in fooClick the image and not the anchor? How should I have done this to use the image.
Whilst the click handler is bound to the anchor, the click event is raised on the image. The event bubbles up the DOM and the event handler on the anchor gets called. event.element() is the element that the event was raised on
Somewhat confused at your question, "Why is the element in fooClick the image and not the anchor? How should I have done this to use the image."
Did you mean "anchor" in the last sentence? If so, event.element() is the actual element that was clicked, not necessarily the element that has the handler assigned to it. If you need the anchor you can just do something like alert(event.element().up('A')).
If you will use images as a background you should get an anchor as event.element().
I think event.element() is a same as event.target and this is an element that received an event first and from which this event is bubble up the DOM. So remove (move it to css/background-image) or check for element() parent.

Categories