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();
}
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});
I know this sounds silly, but I need to create a function that finds a button that has onClick attached to it. And then clicks it.
So like:
<div onclick="coolFunction()" class="coolClass">
<p>Click Me!</p>
</div>
I tried searching for it by doing something like this:
$('.coolClass').attr('onClick') == 'coolFunction()'
Which did actually find it, the problem is I don't understand how can I click on it because it's in an if method.
Your selector would be something more like $('[onclick="coolFunction()"]').
So to do what you describe, you could do this
$('[onclick="coolFunction()"]').trigger('click');
Although, unless coolFunction() cares about being explicitly by this DOM element, you could just call coolFunction(), without having it piggy-back on your click handler.
Update: With an argument
// Note selector is less specific, but still targeted
$('[onclick^="coolFunction"]').trigger('click');
With, this, you can trigger the click handler, and coolFunction(var) in your HTML would work as expected.
if ( $('.coolClass').attr('onClick') == 'coolFunction()' )
{
$('.coolClass').click();
}
$('.coolClass').each(function() {
$this = $(this);
if ($this.attr('onClick') == 'coolFunction()') {
$this.trigger('click')
}
});
This will select all elements with .coolClass, check if the onClick attribute matches the coolFunction call and trigger the click event on that element.
As couzzi said, you can first verify if all the elements of the class coolClass have the attribut coolFunction and when it's the case you can just apply what you want to do on them.
$('.coolClass').each(function() {
$this = $(this);
if ($this.attr('onClick') == 'coolFunction()') {
$this.trigger('click')
}
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
How can I define in jQuery was it a regular click on the same element or double-click?
For example we have element like this:
<div id="here">Click me once or twice</div>
And we need to perform different actions after regular click and double-click.
I tried something like this:
$("#here").dblclick(function(){
alert('Double click');
});
$("#here").click(function(){
alert('Click');
});
But, of course, it doesn't work, everytime works only 'click'.
Then, some people showed me this:
var clickCounter = new Array();
$('#here').click(function () {
clickCounter.push('true');
setTimeout('clickCounter.pop()', 50);
if (clickCounter.length > 2) {
//double click
clickCounter = new Array(); //drop array
} else {
//click
clickCounter = new Array(); //drop array !bug ovethere
}
});
Here we tried to set the interval between clicks, and then keep track of two consecutive events, but this have one problem.. it doesn't work too.
So, someone knows how to do this? or can someone share a link to the material, where I can read about it?
From QuirksMode:
Dblclick
The dblclick event is rarely used. Even when you use it, you should be
sure never to register both an onclick and an ondblclick event handler
on the same HTML element. Finding out what the user has actually done
is nearly impossible if you register both.
After all, when the user double–clicks on an element one click event
takes place before the dblclick. Besides, in Netscape the second click
event is also separately handled before the dblclick. Finally, alerts
are dangerous here, too.
So keep your clicks and dblclicks well separated to avoid
complications.
(emphasis mine)
What you are doing in your question, is exactly how it should be done.
$(".test").click(function() {
$("body").append("you clicked me<br />");
});
$(".test").dblclick(function() {
$("body").append("you doubleclicked me<br />");
});
It works and here is an demo for that.
Since, you want to detect separate single double click. There is a git project for this.
$("button").single_double_click(function () {
alert("Try double-clicking me!")
}, function () {
alert("Double click detected, I'm hiding")
$(this).hide()
})
It adds up events to detect single double clicks.
Hope it helps you now.
I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});