Check if element is hovered over in jQuery - javascript

How can one check if the cursor is hovered over in jquery or js.
I have tried $('#id').is(':hover') but this doesnt seem to be working at all.
I have to mention that i am calling this line inside of a hover() function could this maybe be the problem?
here is my code:
$(document).ready(function() {
/* On hover function, over the menu items */
$('nav ul li').hover(function(){
$('nav ul li').css("background-color", "");
$('#append').css("background-color", "");
$(this).css("background-color", "#9999FF");
$('#append').css("background-color", "#9999FF");
var append;
if($('#menu-item-12')) {
append = 'news';
}else if($('#menu-item-9:hover')) {
append = 'account';
}else if($('#menu-item-11').is(':hover')) {
append = 'check out';
}
$('#appendp').empty();
$('#appendp').append(document.createTextNode(append));
});
Hope someone can tell me whats wrong.
here is jsfiddle link, i did my best :) https://jsfiddle.net/xsv325ef/

A nice way to do it is to store the related texts into an Object literal,
and recall the text depending on the hovered element ID:
fiddle demo
$(function() { // DOM ready shorthand ;)
var $appendEl = $('#appendp');
var id2text = {
"menu-item-12" : "unlock this crap",
"menu-item-9" : "check your gdmn account",
"menu-item-11" : "check the hell out"
};
$('nav ul li').hover(function(){
$appendEl.text( id2text[this.id] );
});
});
Regarding the colors... use CSS :hover

You just need to check if hovered item has this id.
Something like this: https://jsfiddle.net/hrskgxz5/5/
if(this.id === 'menu-item-11') {
append = 'check out';
alert('hovered');
}

$('li').hover(function(){
$(this).css("background-color", "#9999FF");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

You should notice that jQuery .hover() function takes 2 handler function, and here you only provide one. Check the official documentation here.
In your case, you may just use .mouseover() to add a class on top of it, and then set your styles in css file. (Document here)
For example:
$(document.ready(function(){
$('nav ul li').mouseover(function() {
$(this).addClass('active');
});
});
If you do need to toggle the class for that element, the hover function should be as follow:
$(document.ready(function(){
$('nav ul li').hover(function() {
// Stuff to do when the mouse enters the element
$(this).addClass('active');
// Other styles you want to do here
// ...
}, function() {
// Stuff to do when the mouse leaves the element
$(this).removeClass('active');
// Other styles you want to remove here
// ...
});
});
Edit:
As I found out, jQuery .hover() function DO accept single handler. In that case, you'll have to let the class toggle inside:
$(document.ready(function(){
$('nav ul li').hover(function() {
// Stuff to do when the mouse enters the element
$(this).toggleClass('active');
});
});

Related

CSS: Failing to display unless refreshed - Navigation bar

I have been working on navigation bar and the strangest issue is occurring.
Please use the JSFiddle link to see what I mean.
To duplicate the error:
Run the code when the desktop view is active i.e. when the navigation links are in a line.
Then resize the screen till the "click me" is displayed.
Then press it.
Now run the code while you see the "click me" and press it again.
JS information
jQuery(document).ready(function($) {
// UserCP
$('.rotate').on('click', function() {
$(this).toggleClass("down");
});
$('.nav-start').on('click', function() {
$("#nav2").removeClass("hidden");
$('#nav2 li a').stop().slideToggle('100');
return false;
});
$(document).ready(function() {
$('#nav2 li a').stop().slideToggle('100');
});
$('body').on('click', function() {
$('#nav2 li a').stop().slideUp('100');
});
$("#nav2 li a").click(function(e) {
e.stopPropagation();
});
$(document).click(function(event) {
if (!$(event.target).closest('#nav2 li a').length) {
if ($('#nav2 li a').is(":visible")) {
$('html, body').on('click', function() {
$('#nav2 li a').stop().slideUp('100');
});
};
};
});
});
FIXED - UPDATED JSFiddle! Thanks #Louys Patrice Bessette #Titus #Rick
You are using two click events on this "Click me" li...
(One on .navstart and one on .rotate)
It may not be an issue, but this make the code harder to read.
Then, when you slideToggle(), if you want the submenu to slide down, it has to be hidden.
Because, since you remove the hidden class (probably usefull on load), the submenu is visible.
A Toggle hides it.
I simplified your script to this.
Have a look at this updated Fiddle.
$(document).ready(function() {
// Show submenu on "Click me"
$('.nav-start').on('click', function() {
$('.rotate').toggleClass("down");
$("#nav2").removeClass("hidden");
var subNav = $('#nav2 li a');
if(subNav.css("display")=="block"){
subNav.stop().slideUp('100');
}else{
subNav.stop().slideDown('100');
}
return false;
});
$("#nav2 li a").click(function(e) {
e.stopPropagation();
});
// Hide submenu on document click
$(document).click(function(event) {
if (!$(event.target).closest('#nav2 li a').length && $('#nav2 li a').is(":visible")) {
$('#nav2 li a').stop().slideUp('100');
};
});
});

Jquery - How to get elements in a list item

I have the following code:
<li class="shop-currencies">
€
£
$
R
</li>
When an item is clicked I want to set the class to the clicked item and get the ID of the item clicked. This is what I have so far:
$('.shop-currencies').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').each(function(e) {
$(this).removeClass();
});
/**
* Set the class of the clicked element
*/
$( '#' + id).addClass('current');
});
The ID is being returned as 'undefined' How do I get the ID of the clicked link?
Thanks
You need to attach click handler to child anchor element :
$('.shop-currencies a').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').not(this).removeClass('smclass')
/**
* Add class to current elements
*/
$(this).addClass('smclass')
});
There are a couple of options, Milind Anantwar has one, the other is to use the originally clicked element, which is passed to the event as a target property on the event argument. You can also simplify your code a lot. Please note that your bookmark anchors will cause the page to spring to the top, so also add e.preventDefault(); to any solution you choose:
$('.shop-currencies').click(function(e) {
e.preventDefault();
$('a', this).removeClass('current'); // remove related anchor current class
$(e.target).addClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/
The one downside to this is that clicking inside .shop-currencies, but not on a currency link, will clear the current selection. Because of this you are better off targetting the links instead:
$('.shop-currencies a').click(function(e) {
e.preventDefault();
$(this).siblings().removeClass('current'); // remove related anchor current class
$(this).addClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/1/
Which can be reduced to one line:
$('.shop-currencies a').click(function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/2/
Saving the best for last
And one last point... It is more efficient (but hardly noticeable) to add a single delegated event handler, instead of attaching 4 seperate handlers:
$('.shop-currencies').on('click', 'a', function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/3/
Final thoughts:
The IDs on the links are unnecessary if you have an appropriate this available. You can remove them from the HTML. You have the currency value you require in data-currency attributes, so you could use it like this:
$('.shop-currencies').on('click', 'a', function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
alert($(this).data('currency'));
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/7/
your click, is attach to li instead of each a tag
so do $('a').click();instead
Shortest and fastest answer
$('.shop-currencies > a').click(function(){
$(this).siblings('a').removeClass('current');
$(this).addClass('current');
});
The code pen link is here, you can play with the code your self
$('.shop-currencies a').each(function() {
$(this).on("click", function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.shop-currencies a').removeClass("current");
$(this).addClass('current');
alert(id);
});
});
http://jsfiddle.net/nj37g5rm/8/

How can I use jQuery to toggle between 2 classes?

I am not sure toggleClass is the best way to do this, but I have a accordion menu and I am attempting to alternate the icon/image on the right side from a RIGHT arrow to a DOWN arrow.
The first click on the 3 menu items shows the DOWN image (.icon-03) but when I switch between the accordion items it does not go back to the RIGHT arrow image/class (.icon-04).
thoughts?
/* Accordion */
$(document).ready(function () {
$('#accordionFAQ > li > a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#accordionFAQ li ul').slideUp();
$(this).next().slideToggle();
$('#accordionFAQ li a').removeClass('active');
$(this).addClass('active');
//add down arrow
$('> span', this).toggleClass('icon-03 icon-04');
//prevent page reload
e.preventDefault();
}
});
});
Demo JS Fiddle: http://jsfiddle.net/957Fs/
First of all, $(this).attr('class') != 'active' is very inefficient (and possibly fails to work altogether), use $(this).hasClass('active') instead.
After your comment, I re-added the classes - the following should work:
$('#accordionFAQ > li > a').click(function(e){
if (! $(this).hasClass('active') ){
$('.active')
.find('span').toggleClass('icon-03 icon-04')
.end().removeClass('active')
.next().slideUp();
$(this).find('span').toggleClass('icon-03 icon-04')
.end().addClass('active')
.next().slideDown();
//prevent page reload
e.preventDefault();
}
});
When I look at the JSFiddle example it works for me, so I guess it's updated already. I'd like to make a suggestion though: it's perhaps a good idea to just toggle a class (e.g. 'is-active') on your list items and handle the rest with pure CSS. For example:
var $faq = $('#accordionFAQ');
$faq.on('click', '> li > a', function (event) {
$(this).parent().toggleClass('is-active');
});
In your CSS you could do something like this:
#accordionFAQ > li > a span {
// width, height etc
background-position: x y;
}
#accordionFAQ > li.is-active > a span {
background-position: x y;
}
Just an idea; hope it's helpfull.
/* Accordion */
$(document).ready(function () {
var accordionFAQ = $('#accordionFAQ');
// let's use jQuery's .on() rather than .click()
accordionFAQ.find('a').on({
click:function(e){
// prevent the default action
e.preventDefault();
// setup some variables
var that = $(this);
// close open ULs
accordionFAQ.find('ul').slideUp();
// remove .active from other controller
accordionFAQ.find('.active').removeClass('active');
// add .active to clicked controller and show UL
that.addClass('active').next().slideDown();
// remove .right from span
accordionFAQ.find('.right').removeClass('right');
// add .right to current controller's span
that.find('span').addClass('right');
}
});
});
Then, you can have span's default image be the left arrow. and when you add a .right class, it will override the default image with a right arrow using CSS.
hope this helps.

jquery list item class toggle

I have a simple function to toggle list item class from "active" to "inactive". What is the most efficient way (i.e., using the least amount of code) to set all other list items to "inactive" so that there can only be one "active" list item? Please see below for an example. Thank you
<ul class="menu">
<li id="one" class="active">One</li>
<li id="two" class="inactive">Two</li>
<li id="three" class="inactive">Three</li>
<li id="four" class="inactive">Four</li>
<li id="five" class="inactive">Five</li>
</ul>
<script>
$('#one').click(function () {
if ($(this).hasClass("inactive")) {
$(this).removeClass("inactive").addClass("active");
} else {
$(this).removeClass("active").addClass("inactive");
}
});
</script>
This can work:
$('.menu li').click(function () {
$('.menu li').not(this).removeClass('active').addClass('inactive');
$(this).addClass('active').removeClass('inactive');
});
or
$('.menu li').click(function () {
$('.menu li').removeClass('active').addClass('inactive');
$(this).toggleClass('active inactive');
});
The second method is shorter, but slower.
http://jsperf.com/toggle-vs-add-remove
Edit: This one is shorter and faster:
$('.menu li').click(function () {
$('.menu li').not(this).removeClass('active');
$(this).addClass('active');
});
If performance is really a problem you can store your menu in a variable and perform operations on this variable, like:
var $menu = $('.menu li');
$menu.click(function () {
$menu.not(this).removeClass('active');
$(this).addClass('active');
});
For brevity:
$('ul.menu li').click(function () {
$(this).siblings().attr('class', 'inactive').end().toggleClass('inactive active');
});
JS Fiddle demo (127 characters, whitespace-removed character-count: 115).
Character-counts at JS Fiddle, since brevity was the intent, it seems.
Unfortunately, given the problem identified in the comments, below, a corrected implementation is somewhat more verbose than the (currently-accepted answer), alternatives being:
$('ul.menu li').click(function () {
var t = this;
$(this).siblings().add(t).attr('class', function (){
return t === this ? 'active' : 'inactive';
});
});
JS Fiddle demo (174 characters, whitespace-removed character-count: 133).
Or:
$('ul.menu li').click(function () {
var t = this;
$(this).parent().children().attr('class', function (){
return t === this ? 'active' : 'inactive';
});
});
JS Fiddle demo (176 characters, whitespace-removed character-count: 135).
Of course, white space-removed jQuery does become somewhat unreadable, but still: I claim the, uh, moral victory...
References:
add().
attr().
children().
end().
siblings().
toggleClass().
$('ul li').click(function() {
$('ul li').each(function() {
$(this).removeClass('active');
});
$(this).addClass('active');
});
JSFiddle
If SEO is not important and to use the less amount of code I would say use a radio-button list.
Then you can style and interact in JavaScript by using the ":checked" selector.
If you're already using jQuery UI, you can take advantage of the selectable function. That would get you what you want with the least amount of code.
http://jqueryui.com/selectable/

How to add a class onto the selected li element and make li full-sized-clickable

I want to add a class to the selected 'li' and at the same time, remove the class:selected from previous selected li element.
I have worked on it hours and still haven't got any luck. I also checked others questions, but their solutions don't work for me.
Help please....
<ul id='mainView' class='menu' style='float: left; clear: both;'>
<li>Patient</li>
<li>Recommendations</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').className = '';
alert($(this).attr('id'));
$(this).attr('class') = 'selected';
});
});
// $('.menu li').on('click', function () {
// $('.menu li.selected').className = '';
// this.className = 'selected';
// });
</script>
Update:
I did put a inside li, but if I click on the li not the a inside of the li, the webpage does not redirect. That's the reason why I do it in a reversed way.
Update 2
The reason why the selected li does not get the "selected" class is because the whole webpage is redirected to a new page which has the same navigation bar.
So now the question is how to highlight the selected li(it was selected on the previous page) on the new webpage.
Inside an UL everybody (even a browser) is expecting to see a LI
so your HTML:
<ul>
<li>Patient</li>
<li>Recommendations</li>
</ul>
And your jQ:
$('ul li').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
Building web pages you should know how to treat LI elements. Simple, like dummy containers with minimal styling.
That means that you rather add a display:block ... float:left and other cool stuff to the <A> elements, than setting a padding there you go with your full-sized-clickable A elements.
Additionally (if you don't have time to play with CSS) to make a LI fully clickable use:
$('ul li').click(function(){
var goTo = $(this).find('a').attr('href');
window.location = goTo ;
// $(this).addClass('selected').siblings().removeClass('selected'); // than you don't need this :D
});
After the OP late edit - and to answer the question
After the pages refreshes to get which one is the active one use:
// ABSOLUTE PATH
var currentPage = window.location;
// RELATIVE PATH
// var currentPage = window.location.pathname;
$('li a[href="'+ currentPage +'"]').addClass('selected');
<script type="text/javascript">
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').removeClass('selected');
alert($(this).attr('id'));
$(this).addClass('selected')
});
});
</script>
Try addClass and removeClass, they're jQuery functions:
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').removeClass("selected");
$(this).addClass('selected');
});
});

Categories

Resources