General javascript question here, which would also be good to know how(if possible) to do in jquery.
Can you trigger a click event when hovering over an item?
I know there will be people asking why, but please just humour me.
Many thanks,
C
Take a look at the trigger function:
$(someElement).trigger('click');
Just use click()
$(selector).click();
Or, alternatively just move your click() code out into a common function and call that from hover().
Quite simply:
$(selector).mouseenter(function() { $(this).click() });
$('myselector').hover(function(){
$(this).trigger('click');
});
EDIT: way later than the post but just to illustrate how to both add the handler AND trigger it.
$('myselector').on('click',function(){
// handle click event, put money in my bank account
}).on('mouseenter',function(){
$(this).trigger('click'); // only on enter here
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseleave',function(){
// handle mouse leave event of hover, put money in my bank account
}).trigger('click');
Just need it one time?
$('myselector').on('click',function(){
// handle click event, put money in my bank account
}).one('mouseenter',function(){
$(this).trigger('click'); // only on enter here once
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseenter',function(){
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseleave',function(){
// handle mouse leave event of hover, put money in my bank account
});
jQuery can trigger 'click' all object except tag a
let's try this code on console
and see what happen on this page
$('a').bind('mouseover', function(){
$(this).trigger('click');
console.log('hover'); // let me know when it hovering <a>
});
$('#selector').bind('mouseover',function(){
/*DO WHAT YOU WANT HERE*/
});
that should do the trick
It is possible to trigger a click event on hover.
Try the following example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover + (mouseup/mousedown, click) demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p class="up">Press mouse and release here.</p>
<p class="hover1">Press mouse and release here. HOVER+UP/DOWN</p>
<p class="hover2">Press mouse and release here. HOVER.UP/DOWN</p>
<p class="hover3">Press mouse and release here. HOVER.CLICK</p>
<script>
$( "p.up" )
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover1" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
})
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover2" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
});
$( "p.hover2" )
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover3" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
});
$( "p.hover3" )
.click(function() {
$( this ).append( "<span style='color:#00f;'>CLICK.</span>" );
});
</script>
</body>
</html>
You might want to also add a delay on hover so that it won't immediately trigger. Delay will be useful if you are going to use it in a list of thumbnails.
var hoverTimer;
var hoverDelay = 200;
$('.classSelector').hover(function() {
var $target = $(this);
// on mouse in, start a timeout
hoverTimer = setTimeout(function() {
// do your stuff here
$target.trigger('click');
}, hoverDelay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(hoverTimer);
});
Related
I have a few on click events who actually are doing the same thing. Someone told me I should use a case switch for this so I can reduce my code. But I don't know how to do that in combination with a on click event.
$( "#wishlist_top" ).on( "click", function() {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', ['Klikt op "wishlist" in menu']);
});
$( ".wishlist" ).on( "click", function() {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', ['Klikt op "plaats op wishlist"']);
});
$( ".product_size" ).on( "click", function() {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', ['Klikt op "maat advies"']);
});
$( ".product_stock" ).on( "click", function() {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', ['Klikt op "maat niet beschikbaar?"']);
});
if ( $('*').hasClass('404') ) {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', ['Klant is op een 404 pagina gekomen']);
}
Thank you!
While you can use a switch/case for this, it might not be the best idea. You still need to listen for click events on each class/ID, so I'd make a function and call that with the specific string.
Using your code from above, you can make a function like so:
function tagRecording(value) {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', [value]);
}
Now just use a click listener like so:
$( "#wishlist_top" ).on( "click",
function() { tagRecording('Klikt op "wishlist" in menu'); } );
So next time you want to change your code, you just change the tagRecording function (you can rename it however you like).
Another option here is to use data attributes in your markup. Add the message you want to pass to a data-text attribute in each of your elements -
<a href="#" class="product_stock" data-text='Klikt op "wishlist" in menu'>Foo</a>
And then you can set up one JS handler, which grabs the text from your data attribute:
$( ".product_stock" ).on( "click", function() {
window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
hj('tagRecording', $(this).data("text"));
});
Of course this only works if you have control over the creation of the markup.
I have a hidden container that contains comments, and a <div> with a <p> inside that says "Show all comments" that I click to show the comments. When I click the div it shows the hidden comments container perfectly, but when I click it again it doesn't hide the comments container. I am thinking there is something wrong with my jQuery code maybe?
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$( ".see-all" ).click(function() {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
};
When you initialize commentsHidden it is never updated so it always has its initial value. You need to check if its hidden on every click. So you don't need an if statement to attach the event. Just attach a single click event and check inside the event if its hidden and continue accordingly.
$(".see-all").click(function() {
var commentsHidden = $(".comments-container").is(":hidden");
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
When you call on('click', ..) or its shortcut click(..), you install a new handler. What ends up happening is that you have multiple handlers on the same object, and they all get called. Instead, either install the handler only once:
// In global code or code that gets executed upon module load
// Only once!
$(".see-all").click(function() {
if ($( ".comments-container" ).is( ":hidden" )) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
or unbind the old handler:
$( ".see-all" ).off('click'); // Unbind all click handlers
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$( ".see-all" ).click(function() {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
};
You need to check the flag state inside the click function(). The way you have it now will only bind the click handler once on page load.
$( ".see-all" ).click(function() {
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
Try changing to
$( ".see-all" ).click(function() {
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
}
});
The click handler should only be bound once, and you need to check whether comments are hidden each time the p element is clicked.
My home page contains multiple boxes.
On each boxes, when mouseover in or out , the title disappears and the content appears.
It works fine.
The problem is that when mouseovering more than one box on a short period of time, it is a mess.
$( ".views-field-wrapper" ).each(function(){
$( this ).hover(function() {
$( "#front_panel",this ).fadeOut(400);
$( "#back_panel",this ).delay(500).fadeIn(1000);
}, function(){
$( "#back_panel",this ).fadeOut(400);
$( "#front_panel",this ).delay(500).fadeIn(1000);
});
});
How can I stop the previous mouseover reaction when mouseovering another box?
EDIT :
My intial code: http://jsfiddle.net/tz3d6ct6/
Kumar's code that works perfectly with jquery > 1.6 (I must use jquery1.4) http://jsfiddle.net/hrkf5p7w/
Try to use stop() and no need to use loop to bind hover event,
$( ".views-field-wrapper" ).hover(function() { // no need to use each loop
$( "#front_panel",this ).stop(true).fadeOut(400);
$( "#back_panel",this ).delay(500).fadeIn(1000);
}, function(){
$( "#back_panel",this ).stop(true).fadeOut(400);
$( "#front_panel",this ).delay(500).fadeIn(1000);
});
Try it without using using delay() like,
$(".views-field-wrapper").hover(function () { // no need to use each loop
$("#front_panel", this).stop(true).fadeOut(400);
$("#back_panel", this).fadeIn(1000);
}, function () {
$("#back_panel", this).stop(true).fadeOut(400);
$("#front_panel", this).fadeIn(1000);
});
$(".views-field-wrapper").hover(function () { // no need to use each loop
$("#front_panel", this).stop(true).fadeOut(400);
$("#back_panel", this).fadeIn(1000);
}, function () {
$("#back_panel", this).stop(true).fadeOut(400);
$("#front_panel", this).fadeIn(1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='views-field-wrapper type-t nodetype-t'>
<div id='front_panel'>title</div>
<div style='display:none' id='back_panel'>teaser</div>
</div>
I using jquery slidetoggle to show a DIV
but I need set if mouse click not in div.list go close this slideToggle
$( "#list_button" ).click(function() {
$( ".list" ).slideToggle( "fast" );
});
I only found if mouseout.... I cant find how to set if click any "anywhere on the page" to close this toggle
for testing : http://jsfiddle.net/sdgwbyv8/
$( "body" ).click(function( event ) {
if(
event.target.className!='list' && event.target.parentNode.parentNode.className!="list"
) {
$( ".list" ).slideToggle('fast');
}
});
Demo: http://jsfiddle.net/sdgwbyv8/9/ One possible solution, i guess there are better ones....
You can do it by event.stopPropagation():
$("#list_button").click(function (event) {
if ($(".list").is(":hidden")) {
event.stopPropagation();
$(".list").slideToggle("fast");
}
});
$('body').click(function () {
$(".list").hide();
});
$(".list").click(function (event) {
event.stopPropagation();
});
Working Fiddle
I have a <div id="myContainer"></div> .
I also have a button: <input type="button" value="Send" id="sendButton">
While clicking at the button: it replaces the DIV with another:
$( "#sendButton" ).click(function() {
$( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
});
I want to activate another function after click on a new button I've just put (<button id=\"mul\">*</button>):
$( "#mul" ).click(function() {
console.log(' mul clicked!');
});
Which doesn't work, the fact that I'm waiting for a click on a div that just created have something to do with it?
You need to attach event to #mul. Because it is appended dynamically, $("#mul").click() will not work.
.on() attaches event handlers to the currently selected set of elements.
Try:
$("body").on("click","#mul",function(){
console.log("mul clicked!");
});
More information here.
When you call $( "#mul" ).click(), you're attaching an event handler to #mul as it exists at that point. To fix this, just call $( "#mul" ).click() after you create #mul.
$( "#sendButton" ).click(function() {
$( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
$( "#mul" ).click(function() {
console.log( ' mul clicked!' );
});
});
You could also use jQuery's .on method with the optional selector, called a delegated event handler according to the documentation. Take a look at the API for jQuery if that's what you want: jQuery API documentation. The basic usage would be something like
$( document ).on( "click", "#mul", function( ) {
console.log( ' mul clicked!' );
});
use this
$(document).on("click","#mul",function() {
instead of
$( "#mul" ).click(function() {
or
$( "#sendButton" ).click(function() {
$( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
$( "#mul" ).click(function() {
console.log(' mul clicked!');
});
});
$( "#sendButton" ).click(function() {
$( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
// add listener here
$( "#mul" ).click(function() {
console.log(' mul clicked!');
});
$( "#mul" ).trigger("click"); // add this to your code
});
http://api.jquery.com/trigger/ see detail of trigger()
http://jsfiddle.net/tnnj5/ here is a demo
you must add listener after the new content has insert into dom
You can use .live() method to bind event with dynamically added content.
Try this:
$("#mul").live("click", function() {
console.log(' mul clicked!');
});
Try in fiddle
You can also use jquery .on(), But here you add dynamic content. So you need to use event delegation to register the event handler like:
$(document).on("click","body #mul", function() {
console.log(' mul clicked!');
});
Try in jsfiddle with on