Prevent execution of js code on click from other function - javascript

$(document).on('click', '.add-button-prototype', function(){
if ($(this).closest('.collectionContainer').find('input[type="text"]').val() == '') {
return false;
}
});
Example 1 catch click event for all new added element with given class, but not prevent execution of the code.
$('.add-button-prototype').click(function(e){
if ($(this).closest('.collectionContainer').find('input[type="text"]').val() == '') {
return false;
}
});
Second example work only for loaded element with given class and not for new added after init of page. But it prevent execution of the code.
How to catch all element of same class, old and newly added and prevent execution of code if condition are true;

Besides return false add e.preventDefault();
So your code should look like:
$(document).on('click', '.add-button-prototype', function(e){
if ($(this).closest('.collectionContainer').find('input[type="text"]').val() == '') {
e.preventDefault();
return false;
}
});

Related

Changing boolean value on document click

sorry for this very basic question but it's makes me crazy, I don't understand what is not working on this very simple Jquery code.
I just want to change my "abc" boolean from false to true when clicking on my document and launch an alert when "abc" is true (just for exemple).
$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
Somebody to help ? Thanks
This is caused by JavaScript using an event model. This is your piece of code with detailed explanations:
var abc = false;
$(document).click(function() {
// Note that this function is attached to the `click` event
// It will be triggered only when the `click` event is triggered
// This means that the code inside it is not executed at the moment
abc = true;
});
// abc is false at the moment so the if statement won't execute
if (abc == true) {
alert("ALERT");
//do some other things
}
To fix this, just put the if statement inside the click handler and it will work fine.
$(document).ready(function() {
var abc = false;
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your alert won't launch because it is not inside the click handler. It executes only once when document loaded and stays calm. You should move your checking inside click
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
moreover, for boolean values you can directly write the varaible name inside if condition as if expect a boolean anyway
if (abc == true){
can be shorten to
if (abc){
So, after putting all your pieces together,
$(document).ready(function() {
var abc = false;
$(document).click(function() {
abc = true;
if (abc) {
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery function to work on load

I have this function:
$(document).ready(function() {
$('#time-options').on('change', function() {
if ($('#time-options').prop('checked')) {
$('#time-options-div').slideDown(500);
return false;
} else {
$('#time-options-div').slideUp(500);
return false;
}
});
});
So whenever the #time-options is checked, the div slides down. But sometimes the #time-options is already selected when the page loads, so in this case I would like the #time-options-div to be already open.
How can I achieve this?
Try to invoke the change event manually once, after the event got bound.
$('#time-options').on('change', function(){
if($('#time-options').prop('checked')){
$('#time-options-div').slideDown(500);
return false;
}else{
$('#time-options-div').slideUp(500);
return false;
}
}).change();
The simplest way is to also run the block inside the on change function. With some refactoring you can also have:
$(document).ready(function(){
function slide(){
if($('#time-options').prop('checked')){
$('#time-options-div').slideDown(500);
return false;
}else{
$('#time-options-div').slideUp(500);
return false;
}
}
$('#time-options').on('change',slide);
slide();
});

Stop button clicks?

I have two methods
$('.btn-delete').click(function(){
//do A
//return false?
});
$('.btn-delete').click(function(){
//do B
});
How can I stop 'B' from happening when A returns false?
var whatDoesAReturn = false;
$('.btn-delete').click(function(){
if (something) {
whatDoesAReturn = true;
return true;
} else {
whatDoesAReturn = false;
return false;
}
});
$('.btn-delete').click(function(){
if (!whatDoesAReturn) {
// Do whatever
}
});
Use the jquery event's stopImmediatePropagation. That's exactly what it's for:
$('.btn-delete').click(function(e){
//do A
if (a is returning false)
e.stopImmediatePropagation();
});
$('.btn-delete').click(function(){
//do B
});
Why not to put altogether?
$('.btn-delete').click(function(){
//do A
// if true do B
});
You better make a single function and put condition to handle if that is not the solution you can set a flag in first event.
Using single event handler
$('.btn-delete').click(function(){
//do A
if(condition != false)
execute code of second event.
//return false?
});
Using flag
flag = true;
$('.btn-delete').click(function(){
//do A
if (something) {
flag = true;
else
flag = false;
return flag;
});
$('.btn-delete').click(function(){
if(!flag) return;
//do B
});
(Just in case anyone wants a non-jQuery solution).
This can't be done directly in plain JavaScript, because you can't be sure in which order the event listeners will be triggered.
According to the spec,
Although all EventListeners on the EventTarget are guaranteed to be
triggered by any event which is received by that EventTarget, no
specification is made as to the order in which they will receive the
event with regards to the other EventListeners on the EventTarget.
Then, one possibility is joining all handlers inside only one function.
But if that's not possible, you could use event delegation to a wrapper, and stop propagation if necessary:
<div class="btn-wrapper"><button class="btn-delete">Delete</button></div>
­
var btn = document.querySelector('.btn-delete');
btn.addEventListener('click', function(e){
// do A
if(cond) e.stopPropagation();
}, false);
btn.parentNode.addEventListener('click', function(e){
//do B
}, false);

iPad preventDefault action only on first link click

I have a link on my page which I want to behave as follows on the iPad.
On first click only, prevent default action (i.e. should not follow the href action) and on subsequent clicks, follow/allow default action (i.e. should follow the href action).
The code I have written is:
if (navigator.userAgent.match(/iPad/i) != null)
{
var clickCount = 0;
$("a").click(function(event) {
if (clickCount == 0)
{
event.preventDefault();
}
else{
return true;
}
});
clickCount++;
}
Now for some reason, even on first click, it follows the link. How can I fix this?
Try to move clickCount++; into the callback function from the click-event.
$("a").click(function(event) {
if (clickCount == 0){
event.preventDefault();
}
else{
return true;
}
clickCount++;
});
​
Currently, clickCount++; is called when the document is loaded and is already set to 1 when the event gets fired for the first time.

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources