$(function(){
$("#selector").on("someevent", function(){
let variable = some_value;
$("#anotherselector").click(function(){
//code involving variable here
if(condition){
$(this).off(reference to click event here);
}
});
});
});
Is there any way to turn off an event from inside its handler? I'm trying to do something like the code above, and I need it to turn off ONLY that specific click event (each click event is different).
To reference the click event, you can simply pass it 'click' and the selector for which to disable the event:
$(function(){
$("#selector").on("someevent", function(){
$("#anotherselector").click(function(){
if(condition){
$('#anotherselector').off('click');
}
});
});
});
let numHandler = 0;
$('#register').click(function () {
let counter = 0;
let num = ++numHandler;
$('#clickme').click(function handler () {
counter++;
console.log(`Handler ${num} clicked!`);
if (counter == 3) $('#clickme').off('click', handler);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>
You can read more about the off function in the jQuery documentation.
Related
I have a button that triggers an event on a click. Then I have a subscriber to that event. Inside the subscriber's event handler if certain condition is true then I want to stop processing everything inside button's click event.
I tried calling e.preventDefault(), e.stopPropagation() and e.stopImmediatePropagation() but nothing works.
$("#btn").click(function() {
// trigger event
console.log("triggering event");
$(document).trigger("response.beforeSave");
//I want to stop processing after this when subscriber invokes preventDefault() or
//stopPropagation()
console.log("after trigger. This should not get invoked.");
})
$(document).off("response.beforeSave").on("response.beforeSave", function(e) {
console.log("start subscriber");
if (true) // if condition is true
{
//e.preventDefault();
//e.stopPropagation();
e.stopImmediatePropagation();
return;
}
console.log("exit subscriber. This should not get invoked.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click Me</button>
You should create your own Event Object and pass that to the .trigger rather than a string with the event name.
This will allow you to check what happened to the event.
An example exists on the jQuery trigger page
var event = jQuery.Event( "submit" );
$( "form" ).first().trigger( event );
if ( event.isDefaultPrevented() ) {
// Perform an action...
}
Here's your code updated to match:
$("#btn").click(function(e) {
// trigger event
console.log("triggering event");
// create a new event object
var beforeSaveEvent = jQuery.Event("response.beforeSave");
$(document).trigger(beforeSaveEvent);
if (beforeSaveEvent.isImmediatePropagationStopped()) {
console.log("event stopped");
// can also check beforeSaveEvent.isDefaultPrevented
// can also check beforeSaveEvent.isPropagationStopped
// e is the click event - function(e) above
// could also use `event` here
// "cancel" the click event
e.stopPropagation();
return;
}
console.log("after trigger. This should not get invoked.");
})
$(document).off("response.beforeSave").on("response.beforeSave", function(e) {
console.log("start subscriber");
if (true) // if condition is true
{
// whichever is used, check the equivalent event.isXXX
//e.preventDefault();
//e.stopPropagation();
e.stopImmediatePropagation();
return;
}
console.log("exit subscriber. This should not get invoked.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click Me</button>
To put it simple, here's a suggestion by passing arbitrary data (a boolean in your case) via the second parameter of .trigger("EventNamespace", [])
$("#btn").on("click", function(evt) {
const canSave = document.querySelector("[name=canSave]").checked;
$(document).trigger("response.beforeSave", [{canSave}]);
console.log(`Handler before: canSave is ${canSave}`);
if (!canSave) return;
console.log(`Handler after`);
});
$(document).on("response.beforeSave", function(evt, data) {
if (!data.canSave) return;
console.log(`Subscriber: canSave is ${data.canSave}`);
});
<label><input type="checkbox" name="canSave"> toggle "canSave"</label><br>
<button id="btn" type="button">Click Me</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
PS: place $(document).trigger before (like in the example) or after the if(canSave) statement - depending on what you need.
I have a problem: I want to execute the click() event before the mouseenter() event. On mobile devices both work after clicking on an element, but I want mouseenter() to be executed after click().
Here is my code:
$(icon_disabled).click(function() {
if($(disabled_list).hasClass("list-visible-sec")) {
$(disabled_list).removeClass("list-visible-sec");
$(this).removeClass("icons-visible");
} else {
$(disabled_list).addClass("list-visible-sec");
$(this).addClass("icons-visible");
}
});
$(icon_disabled).mouseenter(function() {
$(this).addClass("icons-visible");
$(disabled_list).addClass("list-visible-sec");
});
When you have to trigger an event after another event you can trigger that event inside the callback of 1st event. Here I'm maintaining a counter to prevent multiple event to be activated.
$(document).ready(function(){
let counter = 0;
$('#test').click(function(){
console.log('click');
if(counter === 0){
$('#test').on('mouseenter', function(){
console.log('mouseenter');
counter++;
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<button>click</button>
</div>
I want to store the function reference in a variable and re use it by calling wherever required. Suppose I have a click bound function like this:
var clickEvent = $('#mode').click(function () {
alert("Hello");
});
And I want to reuse it like this:
//call somewhere
clickEvent();
But it is showing an error clickEvent is not a function, why ?
Keep the snippet inside a function , but even in that case the click event won't be triggered.
var x = function() {
$('#mode').click(function() {
alert("Hello");
});
// on call of this function click event will
$("#mode").trigger('click')
}
x()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mode"> Click</button>
With only javascript
var x = function() {
var el = document.getElementById('mode')
el.addEventListener('click', function() {
alert('clicked')
})
el.click();
}
x()
<button id="mode"> Click</button>
$('#mode').click(...) doesn't return a function, it returns the value of $('#mode') so that you can chain method, e.g. $('#mode').click(...).change(...).
If you want a name for the handler function, define it separately:
function clickEvent() {
alert("Hello");
}
and then use it in the event binding:
$("#mode").click(clickEvent);
or call it directly:
clickEvent();
I have a button with class name test-button test-button--check. After clicking test-button--check it should do something and be replaced by class test-button--reset
For test-button--reset I want to write another function, but It doesn't work. Because, the previous function executes again.
$(".test-button--check").on("click", function() {
alert("Check is clicked");
$(this).removeClass("test-button--check").addClass("test-button--reset");
});
$(".test-button--reset").on("click", function() {
alert("Reset is clicked");
$(this).removeClass("test-button--reset").addClass("test-button--check");
});
What can I do?
Thanks
You can write your code inside the document.ready in this way
$(".test-button--check .test-button--reset").on("click", function(e) {
e.preventDefault();
var obj=$(this);
if($(obj).hasClass('test-button--check')){
alert("Check is clicked");
$(this).removeClass("test-button--check").addClass("test-button--reset");
}
if($(obj).hasClass('test-button--reset')){
alert("Reset is clicked");
$(this).removeClass("test-button--reset").addClass("test-button--check");
}
});
Try using .off() to remove an event handler, in this case, it is click.
Should be something like this:
$('.test-button.test-button--reset').off().click(function() {...});
I think this will work:
var check = function checkFunc() {
alert('Check is clicked!');
$(this).addClass('test-button--reset').removeClass('test-button--check');
$('.test-button--reset').unbind('click',check);
$('.test-button--reset').bind('click',reset);
}
var reset = function resetFunc() {
alert('Reset is clicked!');
$(this).addClass('test-button--check').removeClass('test-button--reset');
$('.test-button--check').unbind('click',reset);
$('.test-button--check').bind('click',check);
}
$('.test-button--check').bind('click',check);
Using bind and unbind
I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.
HTML
<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>
Javascript
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
You have a couple of issues here:
Issue #1:
The element does not exist in the DOM to bind to yet, so do any or all of the following:
Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
Use event delegation to bind to events on future elements.
Put all the JavaScript in the ready handler.
Issue #2:
You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.
See the HTML5 spec for button for reference:
Content model:
Phrasing content, but there must be no interactive content descendant.
Instead, bind the click event handler to the button itself.
// Variables
var waarde = {
amount: 2
};
$(document).ready(function(){
updateValues();
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button"><span id="click">0</span></button>
Also, unless you need the span element for something else, you could get rid of it and just use:
document.getElementById("button").innerHTML = waarde.amount;
You should put this code:
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..
You have to write "Click" event in document.ready
var waarde = {
amount: 2
};
$(document).ready(function () {
$('#click').click(function () {
waarde.amount = waarde.amount + 1;
updateValues();
});
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
The problem with your code is you are not assigning an event handler when javascript loads the js file. It should be called in the ready function.
var waarde = {
amount:2
};
$(document).ready(function(){
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
You should wrap it inside the ready method!
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
Here's a codepen link http://codepen.io/anon/pen/vKXQza
Two points:
You should put your jQuery event listener inside the document.ready.
There is no guarantee to work click event on span.
// Variables
var waarde = {
amount:2
};
$(document).ready(function(){
updateValues();
$('#click2').click(function(){
waarde.amount++;
updateValues();
});
});
function updateValues(){
document.getElementById("click2").innerHTML = waarde.amount;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="click2">0</button>
You can see your problem solution is here
You are missing button click event in $(document).ready(function(){}(;