div.onclick = function(data, dom) {
return function() {
if (data.seenAlready == true) { // HACK
$(this).children().toggle();
return;
}
recursiveSearch(data, dom);
// after this onclick, I want to assign it to a toggle like function. no clue how to do it.
}
}(child, mycontainer.appendChild(div));
I'm trying to swap the onclick method after first onclick on a dom element. I've just not had any success, it seems to some sort of closure loss, or something. I'm fine using jQuery.
You have two ways to do this and both ways are by using a jQuery function:
1) Use one API method - this will work just once. You will click it once and then you choose your own second handler and the first one will not fire again e.g.
$(myselector).one(function(){
$(this).click(myotherhandler);
});
Here is the link to this API http://api.jquery.com/one/.
2) You can choose the following way to replace the event handler .
$(myselector).click(function(){
$(this).off();
$(this).click("secondhandler");
});
this will turn the first handler off and will just fire second handler
Check this jsbin:
http://jsbin.com/fekuq/1/edit?html,js,output
Related
I'm trying to write some Javascript to get click event on all elements with class from an array. Everything works fine, but I need it unclickable only until second condition in klikej() function is met. Once the click event fires, then the item with that class shouldn't be clickable. I've tried using removeEventListener and/or handle it with PreventDefaults(), but nothing works. I need to use only vanilla Javascript - no jQuery or anything else. Could you please help me?
poleRandomKaret.forEach(karta => {
document.querySelectorAll(`.${karta}`).forEach(element => {
element.addEventListener('click', event => {
console.log("klik");
klikej(event, element);
});
});
});
function klikej(event, element) {
let kliknuteKarty = document.querySelectorAll('[data-ovoce]');
if (kliknuteKarty.length < 2) {
element.setAttribute('data-ovoce', 'otoceno');
}
kliknuteKarty = document.querySelectorAll('[data-ovoce]');
if (kliknuteKarty.length === 2) {
kliknuteKarty[0].className === kliknuteKarty[1].className ? console.log("yes") : console.log("nope");
kliknuteKarty.forEach(element => {
element.removeAttribute("data-ovoce");
});
}
}
EDIT: The item shouldn't be clickable until the second condition in klikej() function is met. I'm trying to do memory game using vanilla JS. Function klikej() sets data attribute to an item and once there are two items with identical data attributes, it'll print in console "yes". If they're two different data attributes, they needs to be clickable again.
If you remove event listener, and will need to listen again, you would need to add it again or listen with something else. If I would need to recognize if something was clicked, I would add property to the element in the listener callback, so something like:
// before anything else we check if it was clicked before
if (element.clicked) {
// do your magic when element was already clicked
} else {
// do different magic with not yet opened element here
}
// after you did everything needed
// set the clicked attribute to true or false (if you need "unclick" it)
element.clicked = true;
It isn't directly answer to your question but hopefully another view to possible solution - if I understood you correctly, you do something when it was clicked and something else when it wasn't yet clicked and here you have control for both cases.
You can add an option called once as the third parameter of the addEventListener, which makes the event listener execute once.
element.addEventListener('click', function(e){
console.log('clicked'); // This will be executed once.
}, {once: true});
When using onclick in JavaScript to call the function nowClicked(), I need to click the object twice in order for the alert to show. Below is the code for my function.
function nowClicked() {
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
};
What is the problem?
Here's what happens the first time you click your button:
nowClicked is called because you've set it up on the button's onclick
nowClicked sets up a jQuery click handler for .object
The code inside the jQuery click handler only runs the next time you click on the button.
It looks like you are mixing up two ways of handling clicks -- one is using the onclick event, and the second is using jQuery. You need to pick one and stick to it instead of using both.
There is no need to put it inside another function,because click is itself handling a callback function.Remove the outer function nowClicked else remove the $('.object').click(function() {.In the second case you may to pass the context as a function argument.
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
I am working with jaccordian and am wondering how JavaScript can fire a dblclick() when the user fires a single click. The trick is that it should only happen on specific classes.
One can use https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.dispatchEvent in most moddern browsers or just call .trigger - http://api.jquery.com/trigger/ in case you are using jQuery.
i cannot know exactly what you want BUT
if you want the double click to be on a different selector then you can simply do this
$('.your_selector').click(function() {
$('.another_seletor').dblclick();
});
while if you want to fire the double click to the same selector then i you just cal $('selector').click() inside you $('selector').click(function())
here:
$('foo').click(function() {
$('foo').click();
});
finally (i hope this is what you want), the pseudo code is like this:
$(many_selectors).click {
//do a lot of code
//but
if(class of clicked element is foo)
do a double click
}
this case it is the same like the second example but you only need to add the following:
var cls_of_elems_w_dbclk = ['class1','class2','class3'];
var class_of_clicked = $(this).attr("class");
if ($.inArray(class_of_clicked, cls_of_elems_w_dbclk) !== -1) {
//then perform a another click
$(this).click();
}
I have a button, a div and a select combo-box
I want to execute a particular function on click of the button, on mouseenter in div and onchange and blur of the combobox
I do this right now
$("#divID").bind('mouseenter',function(){
// do my stuff
})
$("#comboID").bind('blur change',function(){
// do my stuff
})
$("#buttonID").bind('click',function(){
// do my stuff
})
I do the same stuff everytime. I want to combine all the events together to avoid duplication is there a way to bind each one of the elements with specific events in one statement
I know I can write the code in a separate function and call it each time(solves duplication).
But I want to know can this be done without a separate function and only jQuery
You have seprate event with seprate selectors so one selector or event is not enough, you can map ids and events. I think jquery could not help much to make it single statment.
Live Demo
arrIDs = ['divID','comboID','buttonID'];
arrEvents = ['mouseenter','blur change','click'];
for(idx=0; idx < arrIDs.length; idx++)
$("#" + arrIDs[idx] ).bind(arrEvents[idx], yourFunction);
function yourFunction(event)
{
alert("yourFunction call by " + event.target.id);
}
Not in one statement, since you want to attach different events to different elements. But you can declare a single callback-function that you call for all events.
var callback = function () {
// do my stuff
};
$("#divID").bind('mouseenter', callback);
$("#comboID").bind('blur change', callback);
$("#buttonID").bind('click', callback);
If you don't use jquery you can always set set the other events to be equal to the first.. but good practice will be creating a separate function
There is a link in my webpage, the link itself triggers a function that I could not modify, but I want to make the link, when clicked, also calls another JavaScript function at the same time or preferably after the first function is done. So one click to call two functions...could it be implemented? Thanks
<a title="Next Page" href="javascript:__doPostBack('Booklet1','V4504')">Next</a>
is the sample tag I want to modify, how could make it also call "myFunc" at the same time or preferably after _doPostBack is done.
P.S. the function parameter for _doPostBack such as V4504 is dynamically generated by the ASP user control. So I cannot simply treat it as a static function and bind it with another. I think I could only append some function to it? Unless I parse the whole page first and extract the function name with its current parameters...Since every time I click the link, the parameter such as V4504 changes its value....
Thanks!
You should be able to attach multiple event handlers to a single anchor tag, either with .onclick or .addEventListener('click', function)
https://developer.mozilla.org/en/DOM/element.addEventListener
You can attach a handler to an element click event using plain Javascript in such a way:
function hello()
{
alert("Hello!")
}
var element = document.getElementById("YourAElementID");
if (element.addEventListener)
{
element.addEventListener("click", hello, false);
}
else
{
element.attachEvent("onclick", hello);
}
It supprots all common browsers.
Yes, you can do this MANY ways (I use both $(this) and $('identifier') as you don't say how the functions are bound) :
$(this).click(function(){
my_function_1();
my_function2()
});
Or
$('my element').click(function(){
my_function_1();
});
$('my element').click(function(){
my_function_2();
});
Or, if the functions reside on another object:
$(this).click(function(){
my_function_1();
$('#other_element_id').trigger('click'); //there are a bunch of syntaxes for this
});
Sans JQuery, you can use:
var myObj = document.getElementById('element name');
myObj.addEventListener('click', function(){
alert('first!');
});
myObj.addEventListener('click', function(){
alert('second!');
});
Clicking will result in two sequential alert prompts