Select2 cancel/preventDefault select2:select at specific condition (v.4.0.x) - javascript

I need to add a Button to every select2 item and prevent the default event so only the button gets triggered.
I have the following code but the normal onSelect event still gets triggered:
select.on('select2:select', test2);
function test2(e) {
if (e.params.originalEvent.target.classList.contains('TreeButton')) {
//stop event execution
e.stopPropagation();
e.preventDefault();
return false;
} else {
//execute normal
}
}

Try to catch select2:selecting event:
select.on("select2:selecting", function (e) {
if (e.params.args.originalEvent.target.className === 'btn') {
e.preventDefault();
}
}
Here is a jsfiddle: http://jsfiddle.net/beaver71/dtjhpnm7/

Related

Is there any way to revert preventDefault method in Vanilla JavaScript?

I'm trying to create a horizontal scrolling container. In a precise case i need to revert e.preventDefault(); from a click.
I tried a lot of options, changing 'window.location.href' in the else statement seems to be a great option.
But i can't figure how to grab the href from the link clicked.
Any idea can help to achieve my goal. :)
slider.addEventListener('mouseup', () => {
isDown = false;
// Disable click event (for ever unfortunately)
if(moved === true) {
this.addEventListener('click', (e) => {
e.preventDefault();
});
} else {
// trying to reset click function
}
You can conditionally prevent a click event from firing on your slider by registering a click event listener that shares the moved variable with your mousedown and mousemove event listeners.
The { passive: true } option indicates that the listener does not call event.preventDefault(), and saves a lot CPU time particularly for the mousemove event which can fire several times per second.
The true parameter indicates that the event listener should be called before the event starts to bubble up from the target element. This allows it to prevent propagation even to listeners that were already added on the same element, as long as they didn't also set useCapture to true.
const slider = document.querySelector('input[type="range"]');
// prevent this if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', () => {
console.log('click event fired on slider');
});
// fires just before click event
slider.addEventListener('mouseup', () => {
console.log('mouseup event fired on slider');
});
let moved = false;
// reset for each potential click
slider.addEventListener('mousedown', () => {
moved = false;
});
// indicate cancellation should occur for click
slider.addEventListener('mousemove', () => {
moved = true;
}, { passive: true });
// prevents click event if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', event => {
if (moved) {
event.preventDefault();
event.stopImmediatePropagation();
}
}, true);
<input type="range" />
You should remove the event listener containing the event.preventDefault();.
In order to do that you have to save your function reference into a variable like so:
const preventClickHandler = (e) => e.preventDefault;
slider.addEventListener('mouseup', () => {
isDown = false;
// Disable click event (for ever unfortunately)
if(moved === true) {
this.addEventListener('click', preventClickHandler);
} else {
this.removeEventListener('click', preventClickHandler);
}
})

second or nested event.PreventDefault() not working

I have this jquery code snippet, if I uncomment the first preventDefault() it will work fine, but I'm trying to invoke the second preventDefault(), but it won't work. See below:
$(document).ready(function () {
$('#btnSubmit').click(function (event) {
if ($('#tracking').val() != "") {
// FIRST preventDefault()
//event.preventDefault();
var url = "/ReceivingLog/CheckTrackingNumber?number=" + $('#tracking').val();
$.get(url, null, function (result) {
if (result == "False") {
// SECOND preventDefault()
event.preventDefault();
}
});
}
});
Why is the second/nested preventDefault not working? How do I get the second preventDefault() to work?
$.get is asynchronous - by the time its response comes back, the outer thread has already finished, and the triggered event has completed normally. You'll have to trigger the event again after the response comes back:
const button = document.querySelector('button');
button.addEventListener('click', clickListener);
let doSubmit = false;
function clickListener(e) {
// If this was triggered by the `$.get`, return immediately, run the event as normal without interruption:
if (doSubmit) {
console.log('redirecting');
return;
}
e.preventDefault();
//$.get(url, ...
setTimeout(() => {
const success = true;
if (success) {
doSubmit = true;
button.click();
}
}, 500);
}
<form>
<button type="submit">click</button>
</form>

Understanding how many times the jquery events are called and right handling of keyup event

I am trying to develop my webpage where I have a simple input field where I can type something. I want that when I type something and press "enter", a function gets called. The code I am using is:
$(document).ready(function(){
$("#searchBar").click(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
})
})
Something is not working well. I have 2 questions:
First of all by debugging on the browser I realize that the event "keyup" is called whenever I type any kind of character, but not when I press "enter" and I don't know why.
By always debugging and using a breakpoint on the keyup handler, it happens that when I press a key, in order to get out from the breakpoint I have to resume the script execution once.. then if I type another character and I go again at the breakpoint, I have to resume the script exectuion twice instead of once to continue debugging.. and so on incresing.. why do I have this kind of behavior?
Thanks in advance!
Two problems:
#searchBar only listens to keyUp and Enter if you have clicked on it at least once
#searchBar adds a new keyUp and Enter listener for each time it receives a click event
I'd just bind the events once like so:
$(document).ready(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
});
I can't come up with a valid reason to stop listening to the events, but if that's what you want, then I'd unbind just before or after the call to your searchFunction();
$(document).ready(function(){
$("#searchBar").click(function(e){
$(this).keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$(this).bind("enterKey", function (e) {
searchFunction();
$(this).unbind("enterKey");
$(this).unbind("keyup");
});
});
// but you'd also need to unbind the events if the user clicks somewhere else in the document, otherwise, these events would still get attached every time the user clicks #searchBar
});
But it's unnecessary, as the events are only fired when #searchBar has focus. All these events also detach if you delete #searchBar
Also, why fire "enterKey" when you already are listening for keystrokes?
$(document).ready(function(){
$("#searchBar").keyup(function (event) {
var keycode = event.keyCode || event.which; //this for cross-browser compatibility
if (keycode == 13) {
searchFunction();
}
});
});
I have to resume the script exectuion twice instead of once to
continue debugging.. and so on incresing.. why do I have this kind of
behavior?
You are attaching a new keyup and enterKey event at each click on element.
Remove click event or use .one() to attach click event
$(document).ready(function() {
var search = $("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
or, if one click is intended to begin process
$(document).ready(function(){
var search = $("#searchBar").one("click", function() {
search.keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
})

Jquery how to turn .off() to .on()

I have Jquery click event and i want to prevent multiple click before executing my function UpdateItemStatus(this.id);, so i have tried below code using on/off event,
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
$(this).off(e);
UpdateItemStatus(this.id);
$(this).on(e);
}
});
but how do i turn .on? as it's not working, not able to click again.
How about having a global variable which decides the button click action?
Something like this?
var clickevent = true;
$('#tableItems').on('click', 'tr', function (e) {
if(clickevent){
if ($(e.target).closest("td").hasClass("cssClick")) {
clickevent = false;
UpdateItemStatus(this.id);
clickevent = true;
}
}
});
if UpdateItemStatus function has ajax then i recommend you to put clickevent = true inside success of that ajax
You don't need to use off() for your code. Use return false:
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
return false;
} else{
//do stuff here
}
});
I would probably use something like this :
var inputstate = false;
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
if(!inputstate){
inputstate = true;
setTimeout((function(element){
return function(){
UpdateItemStatus(element);
inputstate = false;
};
})(this),50);
}
}
});
the setTimeout used to "defer the call" of your UpdateItemStatus function.
Because if this listener is fired, (an other listener cannot be fired at the same time) the value of the boolean will change to the end state before that the next click will be handled
Seems like your UpdateItemStatus() uses some asynchronous call (ajax?), so here's how i would do it:
$('#tableItems').on('click', 'tr', function (e) {
var $td = $(e.target).closest("td");
if ($td.hasClass("cssClick")) {
$td.toggleClass("cssClick");
UpdateItemStatus(this.id).done(function(){
$td.toggleClass("cssClick");
});
}
});
and in UpdateItemStatus:
function UpdateItemStatus(id){
//do stuff
return $.ajax(...);
}

How to hook into the page wide click event?

Just like the question states. I want to fire off an event that calls a method everytime the user clicks on the web page.
How do I do that without use of jQuery?
Without using jQuery, I think you could do it like this:
if (document.addEventListener) {
document.addEventListener('click',
function (event) {
// handle event here
},
false
);
} else if (document.attachEvent) {
document.attachEvent('onclick',
function (event) {
// handle event here
}
);
}
Here's one way to do it..
if (window.addEventListener)
{
window.addEventListener('click', function (evt)
{
//do something
}, false);
}
else if(window.attachEvent)
{
window.attachEvent('onclick', function (evt)
{
// do something (for IE)
});
}
$(document).click(function(){});
document.onclick = function() { alert("hello"); };
note that this will only allow for one such function though.

Categories