no href, onclick function for html button - javascript

I am not too advanced in html and javascript. I am just trying to understand, how skyscanner search flights button works. There is no onclick event or function associated with it. Can anyone help me please?
<button class="fss-bpk-button fss-bpk-button--large js-search-button" tabindex="1" type="button">
<span class="bpk-text">Search flights</span>
<span class="bpk-icon-lg bpk-icon-pointer bpk-icon-lg--align-to-button"></span>
</button>

There is no onclick event or function associated with it.
There probably is, it's just:
Added with JavaScript code, not with markup; and/or
On an ancestor element
Most likely #1.
Re #1: Using onclick attributes and such is just one way to put an event handler on a button, and it's a way that's best avoided. Instead, you use modern event handling via addEventListener (or attachEvent on old IE). This might be using the DOM directly, or via a library like jQuery, MooTools, React, Vue, ...
Example using the DOM directly:
document.querySelector(".my-button").addEventListener("click", function() {
console.log("Click!");
});
<button type="button" class="my-button">Click Me</button>
Re #2: click events bubble from the element on which the user clicked to that element's ancestor elements, all the way up to the document element (html). So you can handle that event on an ancestor element, rather than on the button itself. Handling events on an ancestor element is sometimes called "event delegation."
Example:
document.querySelector(".container").addEventListener("click", function(e) {
console.log("Click on '" + e.target.textContent + "'!");
});
<div class="container">
This div contains two buttons. The event handler is on the div, not the buttons.
<div>
<button type="button">One</button>
<button type="button">Two</button>
</div>
</div>

The script is probably called on a button holding "js-search-button" class. There is no need to insert onevent handlers within the HTML element if you can use any script to make use of it.

You can attach events using jQuery or JavaScript.
Below way to attach click event to static element.
$('button[class="fss-bpk-button fss-bpk-button--large js-search-button"]').click(function(){
console.log("clicked!!!");
});
If your element is dynamic then you need to delegate event.
$(document).on('click', 'button[class="fss-bpk-button fss-bpk-button--large js-search-button"]', function(){
console.log("clicked!!!");
});
Hope this will help you.

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()

Click on dynamically added link on KeyUp with jQuery

I use jQuery to add some HTML to the DOM. After the insertion I would like to create an eventhandler which is called on keyup and clicks on the link added to el. However, jQuery does not find the a element as it was added after loading the page.
var el = $("#name");
// add content to el
$(document).keyup(function(e) {
el.find('a').click();
});
How can I update the DOM in el? I know that there is on() (and its predecessors) in jQuery. However, they do not help me as the event is not registered on the added element itself, but on the document and another event just happens on the newly added element. Any ideas on how to solve this?
Thanks to the response of #Johan I was doing further debugging and found the solution:
el.find('a')[0].click();
So the real problem was not the changing DOM but the click() event that apparently can only be applied to a single element and not to a list of only one element.
Some further discussion about click() not firing can be found here: Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Registering an existing event to ajax loaded DOM?

In my homepage , I have this button.
<button class="test">test</button>
And in my current code I have this script
$('.test').on('click',function(){
alert("YOU CLICKED ME");
});
Now, my application is ajaxified, so everytime I click a new page it is loaded as ajax, the problem is that the loaded page also has this button. and its markup is likethis
<div id ="firstDiv>
<div id ="secondDiv">
<button class="test">test</button>
</div>
</div
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
var $bdy=$(document.body);
$bdy.on('click','.test',function(){
alert("YOU CLICKED ME");
});
now append your .test anytime you like
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
Because the handler is attached to the actual element. So if the element is removed and a new element with the same class is created, the event is not associated with that new element.
You could use event delegation to handle this:
$(document.body).delegate('.test', 'click', function(){
alert("YOU CLICKED ME");
});
or
$(document.body).on('click', '.test', function(){
alert("YOU CLICKED ME");
});
(They do the same thing, note the order of arguments is different. I prefer delegate for the clarity, but I think most people use the delegating version of the far-too-overloaded on method instead.)
What that does is watch for the click on document.body, but only fire your handler if the click passed through an element matching that selector (.test, in this case).
As you said that the content is loaded through data you get in AJAX this is the possible scenario that is happening.
<button class="test">test</button> is drawn
Then it is binded to to click event
You load the new data through ajax
Try to bind that it does not.
This is because when you first bind the click event to "test" element with that class are part of the DOM. Now that you add some markup after ajax call the elements become the part of DOM, but now after you wrote the new markup you need to first unbind the click event See Here. And then re-bind the click event. This will bind the event to all elements having class "test".
P.S. I don't know the specifications of your implementation but as others have suggested you should bind events to id and not class.
I finally found out the solution. all I needed to do was define a static container which is this
$('#staticdiv').on('click','.test',function(){
alert("YOU CLICKED ME");
});
and that fixed the issue

How do I assign click handlers to each child with jquery?

<div id="menu">
<div class="menuitem-on" id="home">Home</div>
<div class="menuitem-off" id="mycart">My Cart</div>
<div class="menuitem-off" id="shop">Shop</div>
</div>
how do I assign click handlers to each of the children of menu with jquery?
$("#menu").delegate('div','click', function(){
//do your thing here
});
Handler is on parent, so only one. You can add more div without changing code.
Here is a fiddle page to show a couple of different selector options to get the click anywhere, or just the first level. Shows the use of the event target, currentTarget as well: http://jsfiddle.net/8GLZJ/
Update 3/18/2013 for 1.9.1+ jQuery use:
$("#menu").on('click','div', function(){
//do your thing here
});
You don't want to do that because:
You create a event handler for each children
If you dynamically add more elements, the handler won't work for them.
A better solution is to add a single event handler to the parent element and then do a different action based on the event.target property, that contains the clicked element.
This happens because of event bubbling and it's a cool feature you should take advantage of.
jQuery in particular abstracts this under what they call live events so you should go with those.
$("#menu div").click(function(){
// your code goes here
// $(this) give you the element that was clicked
});
Binding event to each one of element using click() or bind('click', ...) isn't a good solution, because in case if you have, lets say 50 items, you will have to bind 50 same handlers - browser has to register them all.
Better solution is to use feature called event delegation - and jQuery has special method for that - delegate(). So your code will look like this:
$('#menu').delegate('div', 'click', function() {
//code of your handler - 'this' refers to clicked element
});
There is an article with video showing difference between click, live and delegate in jQuery: NetTuts+.
Something like
$("#menu div").on('click', function(){
//alert('clicked');
});

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