JS codes run twice in the page - javascript

These codes are in a html page:
$(".link").click(function() {
alert('hey you');
});
$(".link").click(function() {
alert('hey you');
});
and cause twice alert when .link element is click. Why is it so? And how can I prevent it?

Try with off().
$(".link").off().on("click", function() {
alert('hey you');
});
$(".link").off().on("click", function() {
alert('hey you');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='link'>Test</span>

This below code snippet will give you an ideas whats happening and how can you avoid this. As whenever you code executes it registeres a click handler on the element. So you need to make sure that happens only once. Or you need to remove the existing handlers and the register a new one.
.off and .on see for more details
$(document).ready(() => {
$(".link").click(function() {
alert('hey you');
});
$(".link").click(function() {
alert('hey you 1');
});
$(".link2").click(function() {
alert('hey you 1');
});
$(".link3").off().on("click", function() {
alert('hey you 3');
});
$(".link3").off().on("click", function() {
alert('hey you 4');
});
$(".link3").off().on("click", function() {
alert('hey you 5');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="link">Link1</button>
<button class="link2">Link2</button>
<button class="link3">Link3</button>

if you have something like ajax loader, and want to attach event to newly loaded elements, you can mark the already attached elements so that when you next attach it, you don't re-attach the function.
like this:
function attachEvent(){
$('.class-selector:not(.marked)') // only select element that have not been attached
.addClass('marked') // mark it as attached
.on('click', someFunction); // attach the event
}
function someFunction(){
alert('hohoho');
}
function loadAjax(){
$.ajax({url: 'some-url', success: function(){
// add newly loaded element here
// attach event to them
attachEvent();
});
}
of-course you can use detach and re-attach approach, but this might cause problem when you need to have multiple events on the element

Related

How to modify clickable elements in jQuery?

Why doesn't the on click listener work after clicking on the first list-button?
JSFiddle link
$(".acceptTask").on("click", function(){
acceptTask(this);
});
$(".solveTask").on("click", function() {
solveTask(this);
});
function solveTask(e){
...
}
function acceptTask(e){
...
$(document).on("click", ".solveTask", solveTask);
}
$('.solveTask').on('click', /*...*/) only applies the event handler to anything that has a class "solveTask" at that time. So when you add the solveTask class in your acceptTask function, add an event listener.
$(e).addClass('btn-warning solveTask')
.click(function () { solveTask(this); });
See fiddle: https://jsfiddle.net/1203y34b/1/
I had this problem previously and used 'delegate' instead of 'on':
$(document).delegate('.solveTask', 'click', solveTask)

Differentiating "on" click events in jquery

I have a page which has an event as follows:
$(document).on("click","#div",function(e){
//do the operation
});
This event gets executed on both page load as well as div click.
I need to differentiate between these two calls inside the event, because I have to write a condition extra only on div click and not on load .
How do I know if its from page load or div click?
Edit
On load:
$(default).find('a').trigger("click") ; makes it trigger on load
$(document).on("click", "#div", function(e) {
if (e.originalEvent !== undefined) {//use the originalEvent
alert('human');
} else {
alert('load click')
}
});
$('#div').click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>click</div>
//You can check for originalEvent element present in event object.
$(document).ready(function() {
$(document).on("click","#div",function(e){
if(e.originalEvent) {
alert('clicked manually');
} else {
alert('page load');
}
});
$('#div').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="div">
div
</div>
</body>
You could set a boolean variable in each of these like:
var fromPageLoad = false;
var fromDivClick = false;
$(window).load(function() {
fromPageLoad = true;
//do the operation
});
$(document).on("click","#div",function(e){
fromDivClick = true;
//do the operation
});
and then check which condition is true with an if or a switch statement.
[EDIT]
Unless you want alerts popping out of the blue like the other answers suggest settings variables as so is the way to go.
if u need to perform any action on page load you have to specify as below
$(document).load(function(){
alert("event on page load");
});
if the div click event then as below
$(#div).onclick(function(){
alert ("on div click");
})

Don't work my jQuery code after append

Don't work my jQuery code after append. how can just change js code and worked it?
I don't use from ides "#aaa or #sss", How do without use them?
DEMO: http://jsfiddle.net/sq4kx/
html:
Click Me
<div id="aaa">
<div id="sss">
</div>
</div>
jQuery:
$('.qqq').on('click', function (e) {
e.preventDefault();
$('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
})
$('.auto_box').on('keyup change', '.de1', function () {
alert('This is ok');
})
Try this like,
$('#sss').on('keyup change', '.auto_box .de1', function () {
alert('This is ok');
});
Demo 1
Or
$('.qqq').on('click', function (e) {
e.preventDefault();
$('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
// bind event here
$('.auto_box').on('keyup change', '.de1', function () {
alert('This is ok');
});
});
Demo 2
Try:
$(document).on('keyup change', '.de1', function () {
alert('This is ok');
});
Updated fiddle here.
replace '.auto_box' with document.
$(document).on('keyup change', '.de1', function () {
alert('This is ok');
});
Reason:Why the above code works and yours does not?
1.You are dynamically adding elements.In simpler words,the element you appended did not exist when DOM was loaded.
2.You need to assign Event Delegation for any future addition of elements.The method that we usually use like .click(...) , .on(..) etc only applies to the elements that are currently in the DOM.
3.This is how you provide Event Delegation.
$(document).on('keyup change', '.de1', function(){.........})

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

jQuery: Cannot change style of element after selected

Here is my code. Where you see "alert([...]);", an alert pops up. Why doesn't the CSS style change? The 'click' event doesn't fire either!
resolveSideMenuAddress: function () {
var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:first");
function select(link) {
alert('i alert');
link.css({
'color': '#9a4d9e',
'cursor': 'default'
});
alert('color and cursor not changed');
link.click(function () {
alert('click');
return false;
});
}
if (window.location.pathname === firstLink.attr('href')) {
alert('i alert');
select(firstLink);
}
}
I've tried addClass() and can't change the color of the link that way either.
First, you're not actually firing the click event, but rather applying a click handler to the link. It won't fire until you actually click the link. If you want existing click handlers to be run you can try link.click() (without the function). If you want the link to actually be taken, you should simply set the location to the value of the link's href attribute. Second, I'm not sure why the CSS isn't being applied properly. It looks ok to me. I'd suggest using Firefox/Firebug and inspecting the element after the function has run to see what styles are actually in use.
try using $(link) instead of just link
like this:
resolveSideMenuAddress: function () {
var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:first");
function select(link) {
alert('i alert');
$(link).css({
'color': '#9a4d9e',
'cursor': 'default'
});
alert('color and cursor not changed');
$(link).click(function () {
alert('click');
return false;
});
}
if (window.location.pathname === firstLink.attr('href')) {
alert('i alert');
select(firstLink);
}
}

Categories

Resources