jQuery: trigger a hover event from another element - javascript

When you hover over one <div>, I want an <a> on a separate part of the page to be "hovered" on also.
<div class="initiator">
</div>
<div>
<a class="receiver href="#">Touch the div and I get hovered!</a>
</div>
I've tried this jQuery, but it doesn't trigger the <a>'s hover CSS.
$(".initiator").hover(function(){
$(".receiver").hover();
console.log("div was hovered");
});

Try this:
$('.initiator').on('mouseenter mouseleave', function(e) {
$('.receiver').trigger(e.type);
})
It will apply the same triggers for the receiver as the initiator receives for both mouseenter and mouseleave. Note that:
.hover(over, out)
is just a high-level variant of:
.on('mouseenter', over).on('mouseleave', out)
so using that information you can be more precise when binding and triggering mouse events.
As noted in the comment, you can also use:
$('.initiator').hover(function(e) {
$('.receiver').trigger(e.type);
})
There are lots more to read here: http://api.jquery.com/hover/

You could do something like-:
$(".initiator").hover(function(){
$(".receiver").addClass('hover');
console.log("div was hovered");
}, function(){
$(".receiver").removeClass('hover');
});
And now you can have a class that holds the css rules.

Not sure what you mean by "hovered", but assuming you have some CSS defined for .receiver:hover pseudo class I would suggest to move them to the separate CSS class .hover and use jQuery toggleClass function.
Here is a quick example that makes link text bold when you move mouse over the div - http://jsfiddle.net/Pharaon/h29bh/
$(".initiator").hover(function(){
$(".receiver").toggleClass("hover");
console.log("div was hovered");
});​

hover() is a jQuery method that ties together mouseenter and mouseleave events
try
$(this).find('.receiver').mouseenter()
Or
$(this).find('.receiver').trigger('mouseenter')
However you will likely have far better results adding a class to the a tag and adding a new css rule.
$(this).find('.receiver').toggleClass('hoverClass')

Related

How to call click() for element?

I am using a lightgallery plugin where the click event is defined as:
$(document).on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
self.start($(event.currentTarget));
event.preventDefault();
});
However, when I try to call the event like this:
$(".catalog-content a[data-lightbox='test']").first().trigger('click');
... it doesn't seem to work. What am I doing wrong? How can I trigger the click event?
Example jsFiddle
To "simulate a click" using jQuery, you are correct in that you can just use the .trigger(...) method:
$(".myClass").trigger("click");
The real issue is that you are "clicking" something that doesn't exist. There is no ".catalog-content a[data-lightbox='test' element. As Velthune suggests, you can add the .catalog-content class to the div container to fix this; however, note that there also is no a[data-lightbox='test'] element.
Instead, in your Fiddle you define the following:
<a href="http://..." data-lightbox="350xi" id="test">
something
</a>
So you actually just want to click on the first a element with a data-lightbox attribute of "350xi":
$("a[data-lightbox='350xi']").first().trigger("click");
Hey i have gone through the jsfiddle and updated it please go through it..
$(document).ready(function() {
$(".cars-container a[rel!='']").click(function() {
var rel = $(this).attr("rel");
$(".cars-container a[data-lightbox='" + rel + "']:first").trigger('click');
});
});
click below jsfiddle link to see the working example:-
http://jsfiddle.net/wHJ8E/3/
Your code in fiddle can't work.
1) Either use a different selector as Devendra suggested.
2) Or add the .catalog-content class to the div container:
<div class="cars-container catalog-content">
Fiddle
3) Both Devendra and I can't understand.

can't get a hover event to work on a sibling of a target element using jquery ui duration paramater or CSS

My goal is to change the background color of an element and one of its siblings that is higher in the DOM but in the same parent on hover. I was able to use css transition to change the first element but i couldn't get the sibling to change. so I looked into jquery UI addClass effect
I wanted the code below to work since I couldn't get a css solution to work, the goal was to change both elements on hover
$(document).ready(function(){
$('.circletag').hover(function() {
$(this).addClass( "red");
$(this).parent().find('title').addClass('red', 2000);
}, function() {
$(this).removeClass('red', 5000);
$(this).parent().find('title').removeClass('red', 2000);
});
})
I was able to get a fade effect on the $(this) elements but the .title element is not showing any changes at all.
when .circletag is hovered I would like .circletag backgroud to change and the .title background to change at the same time over a 2 second interval. If It cant be done with css which is the way I would prefer the solution I would appreciate a jquery one.
Also I'm curios to know why the console says
SyntaxError: syntax error
.ui-helper-hidden {
Why does the duration not work in this addClass function when im using jquery ui? So weird for me.
why is it that when the mouse is moves off the element it does not take 5 seconds to remove the class? it looks like the css transition rule is calling the shots.
basically I want the div with the class of .title's backgound and .circletag background to fade in and out on hover of .circletag.
jsfiddle
Thanks for your help guys.
Try it like this:
$(document).ready(function(event){
$('.circletag').hover(function() {
$(this).addClass( "red");
$(this).parent().find('.title').addClass('red', 2000);
}, function() {
$(this).removeClass('red', 5000);
$(this).parent().find('.title').removeClass('red', 2000);
});
})
You need to specify the class selector in 'find' function..
Let me know :)
Try this,
$(this).parent().find('.title').addClass('red', 2000);
you need to use ".title" inside your find() if you are referring a class.
Fiddle
Hope this helps.

Change css when tab has active class

I'm trying to change the background colour of the <body> depending on what tab specific is active.
When a tab is active, a class called 'st_view_active' is added onto the tab content. In the tab content I add a hidden div with the hex code of what my body background colour should be when that tab is active, my jQuery code looks like this:
$(document).ready(function() {
$(function(){
$('body').css('backgroundColor',$('.st_view_active').find('.background').text());
});
});
And my html code when the tab is active is following:
<div class="tab-6 st_view st_view_active" >
<div style="display:none" class="background">yellow</div>
<div class="st_view_inner">
tab 6
</div>
</div>
So when tab6 is active the background of the body should be yellow. However, this is not working, the background colour is not changing, what am I doing wrong here?
DEMO and JSfiddle
Thanks
PS: The red and blue square is the next and previous tab handler..
See here: http://jsfiddle.net/CNYDU/25/
I put the default color at the end of sColor, but you could instead grab the first view and use its color. I did it this way to cut down on testing since your fiddle is painful to work with.
$(document).ready(function() {
var hsh = window.location.hash.replace('#','');
var sColor = hsh ? $("#slidetabs_45").find("."+hsh+" .background").text() : "#3b0";
$("body").css("background-color", sColor);
$("#slidetabs_45").slidetabs({
onContentVisible:function(e){
var color = $("#slidetabs_45").find(".st_view_active .background").text();
$("body").css("background-color", color);
}
});
});
I also added the .st_view_active class to the first view so that it will start correctly.
I also added a CSS3 transition to the background color, which isn't necessary.
This sounds like a great opportunity to use data elements in html. Rather than having a hidden div with the background color you want, you can simple add a data-color attribute to your tab a tag. Then when the div is clicked you can set the color easily with an event handler.
link to an updated fiddle - http://jsfiddle.net/CNYDU/15/
Note: The next and previous tabs do not work in this example, but it should be easy to get them working, just attach a listener to each that runs
$('body').css('background-color', $(".st_tab_active").attr('data-color'));
as its callback.
Check out the livequery plugin for jQuery.
Live Query also has the ability to fire a function (callback) when it matches a new element and another function (callback) for when an element is no longer matched. This provides ultimate flexibility and untold use-cases. For example the following code uses a function based Live Query to implement the jQuery hover helper method and remove it when the element is no longer matched.
Their example:
$('li')
.livequery(function(){
// use the helper function hover to bind a mouseover and mouseout event
$(this)
.hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
}, function() {
// unbind the mouseover and mouseout events
$(this)
.unbind('mouseover')
.unbind('mouseout');
});
You should be able to adapt this to your css changes like fired events, and therefor perform your actions based on which tab is active.
I have forked Jlange's jsfiddle, which uses the data attribute, for a demo of how this plugin would be used:
http://jsfiddle.net/nj6ZY/2/
http://jsfiddle.net/nj6ZY/2/show/#tab-10 - Also works with a link to activate a specific tab
And the relevant bits:
$('.st_tabs_ul li a.st_tab_active').livequery(function(){
$('body').css('background-color', $(this).data('color'));
});
Put ID's on your tabs. Example for id="tab6":
$(document).ready(function() {
if ($('#tab6').attr('class') == 'tab-6 st_view st_view_active') {
$('body').css('background-color', 'yellow');
}
});
However, why would you attach this function to document ready only? I would bind the function to when the element is clicked...

Avoid window jump to top when clicking #-links

I've got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when I click these questions, the window jump to the top of the screen. This is not a huge problem, but I find it annoying, because I have to scroll down to the question again.
The links simply looks like this:
Myquestion
And I've used jQuery and .click as event-listener.
Are there any simple ways to avoid this, or do I have to use .scroll and finding the coordinates of the question? I'd rather avoid this.
EDIT: I know that I can use anchors to do this, but I'd like to avoid any jumping of the screen at all.
You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.
Example:
$("#myID").click(function(e) {
e.preventDefault();
// Do your stuff
});
Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.
You can do it very simple:
Just add ! in the end of your href:
Myquestion
The alternative jQuery ways are:
$("#myID").click(function(e) {
e.preventDefault(); // one way
return false; // second way prevent default click action from happening
});
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
e.preventDefault()alone did not work in older versions of IE.
Actually, the easiest way to do this is to remove the href attribute from your anchor tag. As of HTML5, anchor tags don't need to include href attributes to be semantic.
So
<a id="myID">Myquestion</a>
instead of
Myquestion
This works in IE8+, Chrome, and Firefox. Note that :link css styles won't apply to anchor tags that don't include href attributes.
If you need the href attribute and/or IE7 compatibility, then
$("#myID").click(function(e) {
if(e.preventDefault)
e.preventDefault();
else
e.stop();
});
is probably the best way to go.
$('a').click( function() {
if ($(this).attr("href") == window.location.hash) {
event.preventDefault()
}
});
You are looking for event.preventDefault (see jQuery API).
$(...).click(function(e) {
e.preventDefault();
// your code
});
Example with nice scrolling to answer content:
$("#question_title").click(function(){
var $answer=$("#answer");
$answer.slideDown();
$.scrollTo( $answer, 800 );
return false;
});
I'm used jQuery scrollTo plugin.
Inside your function of:
And I've used jQuery and .click as event-listener.
Will look something like:
$("#myID").click(function(){});
Change this to (don't forget the param e inside function(e):
$("#myID").click(function(e){
e.preventDefault();
});
$('body').on('click', '[href^=#]', function (e) {
e.preventDefault()
});
if the selector ex.."body" is there during the initial render then use the any selector .. id ... to target the general to have jQuery (as of 1.8.2) iterate over. the "On handler invoke a method called "bind" which is used for newly added content to the DOM",. Using the "[href^=#] will select any href that are in the section tag but you can replace section with anything or nothing and it applies a cancellation to the click event. This technique is great for dynamically created content to the DOM
If you add a "\" to the "#" it will prevent from going to the top.
Myquestion
HTML:
<a id="like-post" href="#\">like</a>
JavaScript:
$('body').delegate('#like-post','click',function(e) {
e.preventDefault();
.....
});

fadeToggle next element in on hover

I have the following code to show the next element in the dom on click, I would like to convert this same code into something I could use for a simple hover event. Does jQuery have a simple method to do something like this or should I be using .bind() to mouseover and mouseout events? I know this should be simple, I am probably just not thinking clearly.
$('#el').click(function(e){
e.preventDefault();
var $prevEl = $(this).parent().find('.prev-el');
$prevEl.fadeToggle();
});
One thing to mention is I would like the $prevEl to stay visible after hovering the triggering #el element. What is the best way to go about this?
Thank you in advance,
DT
You can use $('#el').mouseover(... instead of $('#el').click(..., but you should use fadeIn instead of fadeToggle when you're using mouseover:
$('#el').mouseover(function(e) {
var $prevEl = $(this).parent().find('.prev-el');
$prevEl.fadeIn();
});
http://jsfiddle.net/mblase75/eXjTb/3/
If you want it to fade back out on mouseout, though, use .hover as a shorthand way to combine the two and keep the fadeToggle:
$('#el').hover(function(e) {
var $prevEl = $(this).parent().find('.prev-el');
$prevEl.fadeToggle();
});
http://jsfiddle.net/mblase75/eXjTb/2/
this should work:
$('#el').mouseover(function(){
$(this).parent().find('.prev-el').fadeIn();
});
By the way, you can use .next() and .prev() instead of .parent().find(...) (depending on your html)

Categories