How to call a function within a function - javascript

function btn1(){
alert('hello')
}
function btn2(){
alert('anchor')
}
I want to call the function btn1 and function btn2 separate on clicking the div. As it is shown below.
<div onclick="btn2()" style="position:relative">
<div style="width:50%; float:left; height:50px; background:#ddd">
</div>
<input type="button" value="hello" onclick="btn1()"/>
</div>

If I am getting this right you are probably experiencing bubbling. You might want to read about bubbling and event propagation as it will probably be clearer than what I can try to explain. But to solve your issue you want to take a look at jquery's
event.stopPropagation()
http://www.w3schools.com/jquery/event_stoppropagation.asp

The Click Event of the button bubbles his way up to the div. Take a look here how to prevent this:
How to stop event propagation with inline onclick attribute?
I recommend you use addEventListener in favor of inline event handler.

Related

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.

Cancel bubbling on an HTML anchor tag

I have the following set-up on my webpage
<div id="clickable">
Here!
</div>
Is there a way I could use to avoid the click event for the div to be triggered. I presume it has something to do with setting something in the onclick attribute for the anchor tag but trying simple things like e.preventDefault() haven't worked.
Help? Thanks!
e.preventDefault(); wont work in onclick attributes because e is not defined. Also e.preventDefault(); isn't want you want to stop bubbling, you need e.stopPropagation();
Either use;
onclick="$(this).stopPropagation();"
on your anchor, or
$(a).click(function(e){
e.stopPropagation();
});
in your events.
e.preventDefault() does not stop the event from bubbling up. You need to add e.stopPropagation(), or replace it with return false.
You can read more on the differences between these three in this answer.
Vanilla JS expansion on the accepted answer. event.stopPropagation() is the most specific and predictable method for preventing events from bubbling to parent containers without disabling the default behavior. In the following examples, the <a/> will not trigger the alert even though it is contained in a clickable <div/>.
<script>
function linkHandler(event) {
event.stopPropagation()
}
</script>
<div onclick="alert('fail)">
Link
</div>
You can use onclick="return false;"
stuff
You can return false; or make sure your function is using e as an argument
$("#clickable a").click(function(e){
//stuff
e.preventDefault;
});

mouse event problem with nested elements

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>

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

Categories