1 - I've gat an html tag with data-needlogged attribute.
2 - I would like to disable all click events on it.
3 - When the user click on my element, I want to display the authentification popin.
4 - When the user will be logged, I would like to launch the event than I disabled before.
I try something like the following code but it miss the "...?" part.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// 2 - disabled all click events
jQuery('[data-needlogged]').off('click');
// 3 - Add the click event to display the identification popin
var previousElementClicked = false;
jQuery('body').on('click.needlogged', '[data-needlogged]="true"', function() {
previousElementClicked = jQuery(this);
alert('show the identification popin');
return false;
});
jQuery(document).on('loginSuccess', function() {
// 4 - on loginSuccess, I need to remove the "the show the identification popin" event. So, set the data-needlogged to false
jQuery('[data-needlogged]')
.data('needlogged', 'false')
.attr('data-needlogged', 'false');
// 4 - enable the the initial clicks event than we disabled before (see point 2) and execute then.
// ...?
jQuery('[data-needlogged]').on('click'); // It doesn't work
if (previousElementClicked) {
previousElementClicked.get(0).click();
}
});
</script>
Thanks for your help
Thank for your answer.
It doesn't answer to my problem.
I will try to explain better.
When I declare the click event on needlogged element, I don't know if there is already others click event on it. So, in your example how you replace the alert('play'); by the initial event ?
I need to find a way to
1 - disable all click events on an element.
2 - add a click event on the same element
3 - and when a trigger is launch, execute the events than I disabled before.
So, I found the solution on this stackoverflow
In my case, I don't realy need to disable and enable some event but I need to set a click event before the other.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
jQuery.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by #Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};
var previousElementClicked = false;
// set the needlogged as first click event
jQuery('[data-needlogged]').bindFirst('click', function(event) {
//if the user is logged, execute the other click event
if (userIsConnected()) {
return true;
}
//save the click element into a variable to execute it after login success
previousElementClicked = jQuery(this);
//show sreenset
jQuery(document).trigger('show-identification-popin');
//stop all other event
event.stopImmediatePropagation();
return false;
});
jQuery(document).on('loginSuccess', function() {
if (userIsConnected() && lastClickedElement && lastClickedElement.get(0)) {
// if the user has connected with success, execute the click on the element who has been save before
lastClickedElement.get(0).click();
}
});
Related
I have input element which will take input and filter the contents and the filter event will be trigger once the user gets focused out from the input element.
When the user having the focus in the input element and he clicks in one of the button, the click event is invoked first and then the focus out event, as it creates conflicts while generating the filtered content.
I tried changing the order of code and other options such as changing the way of invocation of the click event - none of the ways worked out for me
$('body').on('focusout', '.classname', functionname);
function functionname(e) {
if (typeof e == 'object') {
}
}
$('body').on('click', '.buttonclass', function (e) {});
Could someone help me to build The FocusOut event to trigger first and then the click event.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if button submission should or should not occur.
JS Code:
$("#input").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#button").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('execute your filter)');
});
How to run doSomething() once when scrolling up or scrolling down?
window.onscroll = function(e) {
// scrolling up
if(this.oldScroll > this.scrollY){
doSomething();
// scrolling down
} else {
doSomething();
}
this.oldScroll = this.scrollY;
};
The doSomething() bind some elements and I don't want to do repeat binds. I Just want when on scrolling up, bind once and when on scrolling down bind once.
If you mean, your function should be executed once per each scroll event, then your code should do the job already.
However, if you mean you want your function to only be executed first time when the user scrolls, the code can look like this:
window.onscroll = function(e) {
if (this.oldScroll > this.scrollY) {
doSomething();
} else {
doSomethingElse();
}
this.oldScroll = this.scrollY;
delete window.onscroll;
};
Do NOT rely on any kind of "flag variables" as it is proposed above. It is a very bad practice in this scenario!
You can have an option of defining the closure function and using it in a way like described in this post
Apart from the above post I came across this situation and i used the following method to check if the event is already registered or not see below function where I needed to bind the click once only I used typeof $._data ( elementClose.get ( 0 ), 'events' ) === 'undefined' to get the events registered with the element, $._data is used to retrieve event handlers registered to an element/
this.closeButtonPreview = () => {
let elementClose = $("a.close-preview");
if (typeof $._data(elementClose.get(0), 'events') === 'undefined') {
elementClose.on('click', function(e) {
e.preventDefault();
let container = $(this).parent();
container.find('video').remove();
$("#overlay,.window").effect("explode", {}, 500);
});
}
return;
};
EDIT
Just to get the concept clear for you about the logic I used with $._data(). i created an example below.
What i am doing is binding event click to anchor with id=unique inside the condition if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') { which determines if an event is assigned to the element and binding the event click to the anchor id=multi outside the condition without checking binded events on the element.
What you have to do.
Initially the button unique and multi won't log anything to console, click on EVENT BINDER once and then click on both unique and mutli they both will log text once in console, but as you keep clicking on the EVENT BINDER notice that clicking the multi button will start logging the text as many times as you have clicked the EVENT BINDER button but the unique button will only log once no matter how many times you click on the EVENT BINDER button.
$(document).ready(function() {
$('#binder').on('click', bindEvents);
$('#clear').on('click', function() {
console.clear();
})
});
function bindEvents() {
var uniqueBind = $('#unique-bind');
var multiBind = $('#multi-bind');
//will bind only once as many times you click on the EVENT BINDER BUTTON
//check if any event is assigned to the element
if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') {
uniqueBind.on('click', function() {
console.log('clicked unique bind');
});
}
//will log the text EVENT BINDER * TIMES_EVENT_BINDER_CLICKED button
multiBind.on('click', function() {
console.log('clicked multi bind');
});
}
body {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
EVENT BINDER
CLEAR CONSOLE
<br /><br /><br /><br />
UNIQUE
MULTI
I want to temporarily ignore any click events on a button #firstBtn for 5 seconsd after it has been clicked on.
Template.sidebar.events({
'click #firstBtn': function () {
//...
}
})
How can this be done? Looked into
$('#firstBtn').unbind('click', eventHandler)
Meteor.setTimeout(function(){
$('#firstBtn').bind('click', eventHandler)
}, 5000)
but how should we refer to the click event handler in template sidebar?
Try something like this:
First, initialize a variable to set the timeout, and a variable to say if the button has been clicked. This is needed for the conditional statement.
var timeout = 5000; //5000 milliseconds is equal to 5 seconds
var isClickable = true;
Then, Try some conditional testing like this:
$('#firstBtn').click(function(){
if(isClickable){
...
//standard link handling code
...
isClickable = false;
setTimeout(function(){isClickable = true;},timeout)
}else{
return;
}
});
This will only allow the click event's handling code to execute if the timeout is comeplete.
Good Luck!
So I have a regular onclick event attached to a few buttons, each function that handles the onclick event does something different (so I can't reuse the same function for both events).
element1.onclick = function() {
if(this.classList.contains('disabled') {
return false;
}
// For example make an AJAX call
};
element2.onclick = function() {
if(this.classList.contains('disabled') {
return false;
}
// For example hide a div
};
I'm writing duplicate code for this 'disabled' class check, I want to eliminate this by hooking in some common onclick check then fire the regular onclick event if that check passes.
I know the below won't work but I think it will illustrate what I'm trying to do:
document.addEventListener('click', function() {
// 1. Do the disabled check here
// 2. If the check passes delegate the event to the proper element it was invoked on
// 3. Otherwise kill the event here
});
I'm not using any JavaScript library and I don't plan to, in case someone comes up with 'Just use jQuery' type answers.
EDIT: Had to pass boolean third argument to addEventListener as true and everything is fine.
Use event capturing, like so:
document.addEventListener('click', function(event) {
if (/* your disabled check here */) {
// Kill the event
event.preventDefault();
event.stopPropagation();
}
// Doing nothing in this method lets the event proceed as normal
},
true // Enable event capturing!
);
Sounds like you need to set the capture flag to true and then use .stopPropagation() on the event if a certain condition is met at the target, f.ex:
document.addEventListener('click', function(e) {
if ( condition ) {
e.stopPropagation();
// do soemthing else, the default onclick will never happen
}
}, true);
Here is a demo: http://jsfiddle.net/v9TEj/
You can create a generic function that receives a callback:
//check everything here
function handleOnclick(callback) {
if(this.classList.contains("disabled")) {
return false;
} else {
callback(); //callback here
}
}
//and now on every onclick, just pass the custom behavior
element1.onclick = function() {
handleOnClick(function() {
console.log('element1 onclick fire'); // For example hide a div
});
};
element2.onclick = function() {
handleOnClick(function() {
console.log('element2 onclick fire'); // For example ajax request
});
};
Edit
Based on your latest comment, let me know if this rewrite works for you... only one biding this time.
element1.customFunction = function() {
handleOnClick(function() {
console.log('element1 onclick fire'); // For example hide a div
});
};
element2.customFunction = function() {
handleOnClick(function() {
console.log('element2 onclick fire'); // For example ajax request
});
};
document.addEventListener('click', function() {
//1. grab the element
//2. check if it has the customFunction defined
//3. if it does, call it, the check will be done inside
};
I have this function:
$("#border-radius").click(function(){
var value = $("#border-radius").attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, '2', this.id)
$(this).css({
"-webkit-border-radius": value
});
});
});
It reads the value of a textbox,
input type="text" id="border-radius" value="20px"
...and does a few things with it that are not relevant to my problem.
The textbox has the id="border-radius", and when it is clicked (and has a value) the function executes, as shown: $("#border-radius").click(function(){ ...do some stuff...
Basically, I want to be able to type a value into the textbox, and then click an object (submit button or div, preferably a div) and have it execute the function after: $("#border-radius").click(function(){ ...do some stuff... Instead of having to click the textbox itself
What can I add/change to enable this?
I think you need to identify the event target.
that you can do it by
event target property
example
$(document).ready(function() {
$("#border-radius").click(function(event) {
alert(event.target.id);
//match target id and than proceed futher
});
});
Put the click handler on #my-button or whatever your button is.
$("#my-button").click(function(){
var value = ... /* your original code */
});
It will still work because you are getting the value like $("#border-radius").attr("value"); and not $(this).attr("value");. So you all you need to change is which element you attach the click function to.
Alternatively, if you want to keep both handlers, you can just use it for both elements like this:
var commonHandler = function(){
var value = ... /* your original code */
};
$("#border-radius").click(commonHandler);
$("#my-button").click(commonHandler);
You can also trigger the click event of #border-radius, but this will execute all the event handlers attached on it:
$("#my-button").click(function () {
$("#border-radius").click();
// or $("#border-radius").trigger('click');
});