On() and off() - Jquery - javascript

Trying to understand Jquery's On() and off() a little better. Not understanding why this is not working. I want to activate and inactivate id TurnON and TurnOff Js.
Javascript
$(document).ready(function(){
$(document).on("click.turnon","#TurnOn",function() {
$(document).off('click.turnon');
alert("Turn Off is now turned off");
});
$(document).on("click.turnoff","#TurnOff",function() {
$(document).on('click.turnon');
alert("Turn Off is now turned back on");
});
});
HTML
<div id="TurnOn">Turn Off</div>
<div id="TurnOff">Turn On</div>

If you want an event handler to only fire once then take a look at .one(): http://api.jquery.com/one
As of jQuery 1.7 it does event delegation.
$(function(){
$(document).one("click.turnon","#TurnOn",function() {
alert("Turn Off is now turned off");
});
$(document).one("click.turnoff","#TurnOff",function() {
alert("Turn Off is now turned back on");
});
});
Here is a demo using .one(): http://jsfiddle.net/9qxfT/1/
Also, your code was just about right but you have a couple typos here:
$(document).on("click.turnoff","#TurnOff",function() {
$(document).on('click.turnon');
alert("Turn Off is now turned back on");
});
$(document).on('click.turnon'); should be: $(document).off('click.turnoff');
Here is a demo of these small changes: http://jsfiddle.net/9qxfT/
Update
You can save the state with a variable:
$(function(){
//declare a variable to save whether or not the `#TurnOn` element is 'on' (true) or 'off' (false)
var isOn = true;
$(document).on("click.turnon","#TurnOn",function() {
//check to see if the flag is set to true, which means the `#TurnOn` element is 'on' already
if (isOn) {
alert("#TurnOn is already turned on");
//otherwise set the `#TurnOn` element to 'on'
} else {
alert("#TurnOn is now turned back on");
isOn = true;
}
});
//set the `#TurnOn` element to `off` when the `#TurnOff` element is clicked
$(document).on("click.turnoff","#TurnOff",function() {
isOn = false;
alert("#TurnOn is now turned off");
});
});​
Here is a demo: http://jsfiddle.net/9qxfT/4/

Your logic is right, but may I suggest better implementation?
Please read this page as well: http://api.jquery.com/off/
Here is what I suggest:
// first put a .click event with a separate "ID" to enable another div "ID".
$('#ButtonForTurnOn').click(function () {
//while body is .on(), the ID, when clicked applies whatever effects
$("body").on("click", "#TurnOn", onlight).find("#TurnOn").addClass("clickable").text("ON switch on");
});
// enable OFF switch
$('#ButtonForTurnOff').click(function () {
$("body").on("click", "#TurnOff", offlight).find("#TurnOff").addClass("clickable").text("OFF switch on");
});
Now, for you to have an effective .off function, YOU MUST have the
"selector string match the one passed to .on() when the event handler
was attached."
For example:
If your $("body").on() is this,
$("body").on("click", "#TurnOff", function({
// stuff here
});
Your $("body").off() should be this,
$("body").off("click", "#TurnOff", function({
// stuff here
});
Try out this jsfiddle
Hope this helps explain things!
Just think of it as disabling something, until its turned back on.

Related

Execute jquery function by id when id is changed by jquery

It's possible to change an id of html balise with this function :
$("#test").attr('id', 'test2');
My exemple code is :
$("#test").click(function() {
$("#test").attr('id', 'test2');
alert('test');
return false;
});
$("#test2").click(function() {
$("#test2").attr('id', 'test');
alert('test2');
return false;
});
The first function work normally but when the id is changed the second function is not run ...
Can you help me please ?
Thanks,
You need to use event delegation:
$("body").on('click','#test2',function() {
$("#test2").attr('id', 'test');
alert('test2');
return false;
});
The event handler is bound to the element itself, not it's attributes like id or class. So even if you change an attribute which you used to bind the event, the handler will remain with the element.
So in my opinion it's better to re-use the existing handler by condition checking. for example,
$("#test").click(function () {
if (this.id == "test") {
alert('test');
this.id = 'test2';
} else {
alert('test2');
this.id = 'test';
}
return false;
});
No need to bind extra handler to another element. This should be:
faster (No delay of bubbling)
memory efficient (Less number of handlers)
when talking about complex DOM structure with hundreds of elements.

Adding an on event to an e.currentTarget?

A variety of elements on my page have the content editable tag.
When they are clicked I do this:
$('[contenteditable]').on('click', this.edit);
p.edit = function(e) {
console.log(e.currentTarget);
e.currentTarget.on('keydown', function() {
alert("keydown...");
});
};
I get the current target ok, but when I try to add keydown to it, I get the err:
Uncaught TypeError: undefined is not a function
It's a native DOM element, you'll have to wrap it in jQuery
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
e.currentTarget should equal this inside the event handler, which is more commonly used ?
It's a little hard to tell how this works, but I think I would do something like
$('[contenteditable]').on({
click : function() {
$(this).data('clicked', true);
},
keydown: function() {
if ($(this).data('clicked'))
alert("keydown...");
}
});
Demo
First issue is you are trying to use jQuery methods on a DOM element. Second issue is I do not think you want to bind what is clicked on, but the content editable element itself.
It also seems weird to be adding the event on click instead of a global listener. But this is the basic idea
$(this) //current content editable element
.off("keydown.cust") //remove any events that may have been added before
.on('keydown.cust', function(e) { //add new event listener [namespaced]
console.log("keydown"); //log it was pressed
});
Edited: I had a fail in code. It works fine now.
Getting your code, I improved to this one:
$(function(){
$('[contenteditable]').on('click', function(){
p.edit($(this));
});
});
var p = {
edit: function($e) {
console.log($e);
$e.on('keydown', function() {
console.log($(this));
alert("keydown...");
});
}
}
You can check it at jsFiddle
You need to wrap the e.currentTarget(which is a native DOM element) in jQuery since "on" event is a jQuery event:
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
EDIT:
$('[contenteditable]').on('click', p.edit);
p.edit = function(e) {
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
};
You're defining p.edit AFTER $('[contenteditable]').on('click', p.edit); resulting in an error since p.edit doesn't exist when declaring the on.
In case you don't know, you are defining p.edit as a function expression, meaning that you have to define it BEFORE calling it.

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

jQuery, Triggering event from Class

Please take a look at the following code and fiddle.
CODE
$("#enable").click(function(e) {
if (!$("#enable").data('isOn')) {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '1px solid red');
$(this).addClass('clickEnabled');
});
$("#enable").data('isOn', true);
} else {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '');
$(this).removeClass('clickEnabled');
});
$("#enable").data('isOn', false);
}
});
$(".clickEnabled").click(function(e) {
alert('clicked');
});
Fiddle: http://jsfiddle.net/qAuwt/
I am basically trying to toggle a "clickEnabled" class on elements when a button is pressed. The toggling is working as the border is changing however the clickEnabled class is not responding to click events
There are no .clickEnabled elements when you set the event handler. You can still catch the click event, though:
$(document).on("click", ".clickEnabled", function(){
alert("Hello, world!");
});​
Change:
$(".clickEnabled").click(function (e) {
alert('clicked');
});
To:
$(".clickable").click(function (e) {
if ( $(this).hasClass("clickEnabled") )
{
alert('clicked');
}
});
As #araxanas mentioned, the .clickEnabled don't exist on load. So I switched the selector to .clickable, which do. However, you only want to handle the click when they're enabled. That's why I've added the conditional. It'll only alert if the clicked element has the clickEnabled class.
Also, it might help to move the css out of javascript, that way you can see visually if the class is there or not, see my updated fiddle.
The problem is that when page loaded, the click event handler binds to no elements (because there is no element with class 'clickEnabled').
The solution is to change the .click() method to .live() method:
$(".clickEnabled").live('click', function (e) {
alert('clicked');
});

What is the opposite of evt.preventDefault();

Once I've fired an evt.preventDefault(), how can I resume default actions again?
As per commented by #Prescott, the opposite of:
evt.preventDefault();
Could be:
Essentially equating to 'do default', since we're no longer preventing it.
Otherwise I'm inclined to point you to the answers provided by another comments and answers:
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
How to reenable event.preventDefault?
Note that the second one has been accepted with an example solution, given by redsquare (posted here for a direct solution in case this isn't closed as duplicate):
$('form').submit( function(ev) {
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
function(evt) {evt.preventDefault();}
and its opposite
function(evt) {return true;}
cheers!
To process a command before continue a link from a click event in jQuery:
Eg: Click me
Prevent and follow through with jQuery:
$('a.myevent').click(function(event) {
event.preventDefault();
// Do my commands
if( myEventThingFirst() )
{
// then redirect to original location
window.location = this.href;
}
else
{
alert("Couldn't do my thing first");
}
});
Or simply run window.location = this.href; after the preventDefault();
OK ! it works for the click event :
$("#submit").click(function(event){
event.preventDefault();
// -> block the click of the sumbit ... do what you want
// the html click submit work now !
$("#submit").unbind('click').click();
});
event.preventDefault(); //or event.returnValue = false;
and its opposite(standard) :
event.returnValue = true;
source:
https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue
I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
I would suggest the following pattern:
document.getElementById("foo").onsubmit = function(e) {
if (document.getElementById("test").value == "test") {
return true;
} else {
e.preventDefault();
}
}
<form id="foo">
<input id="test"/>
<input type="submit"/>
</form>
...unless I'm missing something.
http://jsfiddle.net/DdvcX/
This is what I used to set it:
$("body").on('touchmove', function(e){
e.preventDefault();
});
And to undo it:
$("body").unbind("touchmove");
There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.
Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).
As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.
See below for an explanation:
;(function($, window, document, undefined)) {
$(function() {
// By default deny the submit
var allowSubmit = false;
$("#someform").on("submit", function(event) {
if (!allowSubmit) {
event.preventDefault();
// Your code logic in here (maybe form validation or something)
// Then you set allowSubmit to true so this code is bypassed
allowSubmit = true;
}
});
});
})(jQuery, window, document);
In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.
This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.
Here's something useful...
First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.
Google
<script type="text/javascript">
$(document).ready(function() {
$("#link").click(function(e) {
// Prevent default action
e.preventDefault();
// Here you'll put your code, what you want to execute before default action
alert(123);
// Prevent infinite loop
$(this).unbind('click');
// Execute default action
e.currentTarget.click();
});
});
</script>
None of the solutions helped me here and I did this to solve my situation.
<a onclick="return clickEvent(event);" href="/contact-us">
And the function clickEvent(),
function clickEvent(event) {
event.preventDefault();
// do your thing here
// remove the onclick event trigger and continue with the event
event.target.parentElement.onclick = null;
event.target.parentElement.click();
}
I supose the "opposite" would be to simulate an event. You could use .createEvent()
Following Mozilla's example:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var cancelled = !cb.dispatchEvent(evt);
if(cancelled) {
// A handler called preventDefault
alert("cancelled");
} else {
// None of the handlers called preventDefault
alert("not cancelled");
}
}
Ref: document.createEvent
jQuery has .trigger() so you can trigger events on elements -- sometimes useful.
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.
$('.btnEdit').click(function(e) {
var status = $(this).closest('tr').find('td').eq(3).html().trim();
var tripId = $(this).attr('tripId');
if (status == 'Completed') {
e.preventDefault();
alert("You can't edit completed reservations");
} else if (tripId != '') {
e.preventDefault();
alert("You can't edit a reservation which is already attached to a trip");
}
//else it will continue as usual
});
jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.
jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.
$( selector ).on("submit.my-namespace", function( event ) {
//prevent the event
event.preventDefault();
//cache the selector
var $this = $(this);
if ( my_condition_is_true ) {
//when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
$this.off("submit.my-namespace").trigger("submit");
}
});
now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..
you can use this after "preventDefault" method
//Here evt.target return default event (eg : defult url etc)
var defaultEvent=evt.target;
//Here we save default event ..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
You can always use this attached to some click event in your script:
location.href = this.href;
example of usage is:
jQuery('a').click(function(e) {
location.href = this.href;
});
In a Synchronous flow, you call e.preventDefault() only when you need to:
a_link.addEventListener('click', (e) => {
if( conditionFailed ) {
e.preventDefault();
// return;
}
// continue with default behaviour i.e redirect to href
});
In an Asynchronous flow, you have many ways but one that is quite common is using window.location:
a_link.addEventListener('click', (e) => {
e.preventDefault(); // prevent default any way
const self = this;
call_returning_promise()
.then(res => {
if(res) {
window.location.replace( self.href );
}
});
});
You can for sure make the above flow synchronous by using async-await
this code worked for me to re-instantiate the event after i had used :
event.preventDefault(); to disable the event.
event.preventDefault = false;
I have used the following code. It works fine for me.
$('a').bind('click', function(e) {
e.stopPropagation();
});

Categories

Resources