How can I highlight a selected list item with jquery? - javascript

I have several items in a list and want to highlight the one a user clicks on by applying some css style, maybe a background color etc.
My HTML looks like this:
<ul class="thumbnails">
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb1.jpg' alt="">
<span class="gifttitle">Thumb1</span>
</a>
</li>
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb2.jpg' alt="">
<span class="gifttitle">Thumb3</span>
</a>
</li>
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb3.jpg' alt="">
<span class="gifttitle">Thumb3</span>
</a>
</li>
</ul>
jQUery to retrieve selected item:
$('.thumbnail').click(function(e) {
e.preventDefault();
???
})

You could use jQuery's class management methods (namely addClass() and removeClass() in this case) to add a class on the selected item and remove the same class from all the other items (if you want only one selected at a time).
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'highlight';
//.click() will return the result of $('.thumbnail')
//I save it for future reference so I don't have to query the DOM again
var $thumbs = $('.thumbnail').click(function(e) {
e.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.thumbnail')
//instead of the saved $thumbs
$thumbs.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
});
Then in your CSS just add:
.highlight {
background-color: cyan;
font-weight: bold;
}
jsFiddle Demo
This is a better solution than changing CSS properties directly from jQuery/Javascript (with the .css() method for example), because separation of concerns will make your code more manageable and readable.

$('.thumbnail').click(function(e) {
e.preventDefault();
$(this).css('background-color', 'red');
})

Your ??? would be:
$('.thumbnail').removeClass('selected');
$(this).addClass('selected');
Then all you have to do is define your 'selected' css class.

If you don't need the active to be persistent here's a CSS way:
li:focus{
background: red;
}
li:active{
background: gold;
}
<ul>
<li tabindex="1">Item 1</li>
<li tabindex="1">Item 2</li>
<li tabindex="1">Item 3</li>
</ul>
Now click <b>here</b> and see why it's not persistent.
in some situations the above might be useful - to only highlight the currently "click-active" item…

Related

Loop through DOM elements with JQuery to assign a click handler

I need to loop through the DOM with JQuery, and add a click handler to multiple parent elements that contain a child that will also be given a slideToggle(). I have the logic working fine when I add the click handlers manually, but now I need to be able to dynamically do this to multiple parent elements.
Here is my HTML:
<div class="map-poi-nav">
<ul class="map-poi-nav-dropdown">
//Parent #1
<li class="sub-menu-link" id="sub-menu-link-1">
<a href="#">
<img src="https://svgshare.com/i/ADc.svg"> Activities
</a>
</li>
<li class="sub-menu">
<ul class="sub-menu-list" id="sub-menu-list-1">
<li><a><span>•</span>Golden State Park</a></li>
<li><a><span>•</span>Sunrise Oaks City Park</a></li>
</ul>
</li>
</ul>
<ul class="map-poi-nav-dropdown">
//Parent #2
<li class="sub-menu-link" id="sub-menu-link-2">
<a href="#">
<img src="https://svgshare.com/i/ADc.svg"> Dining
</a>
</li>
<li class="sub-menu">
<ul class="sub-menu-list" id="sub-menu-list-2">
<li><a><span>•</span>The Loft Grill</a></li>
<li><a><span>•</span>Fish Grill & Bar</a></li>
</ul>
</li>
</ul>
</div>
Basically, you click on .sub-menu-link to slideToggle() .sub-menu-list.
Here is the JS that I have working so far. It targets the id's manually currently, which feels gross:
$('#sub-menu-link-1').click(function() {
$('#sub-menu-list-1').slideToggle(100);
$(this).toggleClass('active-menu-link');
});
$('#sub-menu-link-2').click(function() {
$('#sub-menu-list-2').slideToggle(100);
$(this).toggleClass('active-menu-link');
});
My apologies if this is something very apparent to do in JQuery. I am not at all familiar with it, and it just so happens to be a requirement of this project.
you could simply use below code.
select all list items with class name and add listener. click will be attached to all elements
$('.sub-menu-link').click(function() {
$(this).slideToggle(100);
$(this).toggleClass('active-menu-link');
});
You already have classes, so just use them instead of the ids: use this to refer to the clicked element, .next() to get the next sibling (the li.sub-menu), and .find('.sub-menu-list') to get to the ul you want to toggle:
$('.sub-menu-link').click(function() {
const $subMenuList = $(this).next().find('.sub-menu-list');
console.log($subMenuList.text().trim());
$subMenuList.slideToggle(100);
$(this).toggleClass('active-menu-link');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="map-poi-nav">
<ul class="map-poi-nav-dropdown">
//Parent #1
<li class="sub-menu-link" id="sub-menu-link-1">
<a href="#">
<img src="https://svgshare.com/i/ADc.svg"> Activities
</a>
</li>
<li class="sub-menu">
<ul class="sub-menu-list" id="sub-menu-list-1">
<li><a><span>•</span>Golden State Park</a></li>
<li><a><span>•</span>Sunrise Oaks City Park</a></li>
</ul>
</li>
</ul>
<ul class="map-poi-nav-dropdown">
//Parent #2
<li class="sub-menu-link" id="sub-menu-link-2">
<a href="#">
<img src="https://svgshare.com/i/ADc.svg"> Dining
</a>
</li>
<li class="sub-menu">
<ul class="sub-menu-list" id="sub-menu-list-2">
<li><a><span>•</span>The Loft Grill</a></li>
<li><a><span>•</span>Fish Grill & Bar</a></li>
</ul>
</li>
</ul>
</div>
You can use jQuery's .next() like so:
$(".sub-menu-link").click(function() {
$(this).next(".sub-menu-link").slideToggle(100);
$(this).toggleClass("active-menu-link");
})
Or you can chain them and use ES6 arrow syntax to make it more concise:
$(".sub-menu-link").click(() => $(this).toggleClass("active-menu-link").next(".sub-menu-link").slideToggle(100));
You should try this if your list and link ids have similiar pattern as in the code you have shown
$('#sub-menu-link').click(function() {
var id = $(this).attr("id").replace("sub-menu-link", "")
$('#sub-menu-list-'+ id).slideToggle(100);
$(this).toggleClass('active-menu-link');
});

Append a child element to another div while having a reference to the orginal parent element

I have this html code
<div id="left-container" class="w3-container w3-left">
<div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
<h1>Give</h1>
<h3>Selected Definition:</h3>
<ul style="display:none;">
<li> offer in good faith </li>
<li> inflict as a punishment </li>
<li> afford access to </li>
</ul>
</div>
<div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
<h1>Up</h1>
<h3>Selected Definition:</h3>
<ul style="display:none;">
<li> to a higher intensity </li>
<li> to a later time </li>
<li> used up </li>
</ul>
</div>
</div>
<div id="right-container" class="w3-container w3-right"></div>
I want the user, once he click on one of the wordDiv's, to be able to see the potential definitions of that word in the right container (which are found in the "ul" element of each "wordDiv"), select one of the definitions, then I want to display the selected definition in the original wordDiv in the left-container.
You can found Jsfiddle Demo Here
A solution using jQuery. Updated Fiddle
$(function() {
$('.wordDiv').click(function() {
var txt = $(this).find('ul').html();
$('#right-container').html('<ul>' + txt + '</ul>')
})
})
Please check this fiddle
I have added li elements to another div based on the div which you are selected.
You can use the jQuery this variable in the click function, here is a working jQuery example of your request Updated Fiddle
It puts the li elements in the right div AND adds the onclick listener, which has the knowlege of its origin ;)
$('h1').click(function(){
var origin=$(this);
$(this).siblings('ul').children().click(function(){
$(this).parent().hide();
$(origin).parent().append(this);
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})
$(this).siblings('ul').show();
$("#right-container").append($(this).siblings('ul'));
})
$('ldi').click(function(){
$(this).parent().hide();
$(this).parent().parent().append(this);
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})

Change max height element after it being clicked

I'm writting a dropdown menu and I wanted to have the dropdown being controlled by javascript.
My dropdown has the sub menu hidden of sight max-height: 0px; and when the correspondent anchor tag is clicked, I change its max-height parameter to 400px, using the following function:
function drop_down(name) {
document.getElementById(name).style.maxHeight = "400px";
}
So far so good. The problem is that the element's max-height, stays at 400px and the sub menu does not hide. So I thought that I should target the click of the mouse and when this happens check if there is any element with 400px and change it back to 0.
$('html').click(function() {
var max_h = document.getElementsByClassName("nav_content");
var i;
for(i = 0 ; i < max_h.length ; i++)
{
if(max_h[i].style.maxHeight == "400px")
{
max_h[i].style.maxHeight = "0px";
}
}
});
What happens is that this function tracks every click, even the one used to display the sub menu. So my question is: is there a way to only activate the second function after I clicked my sub-menu? Because I always want the click that comes after the menu is displayed to close the sub menu.
HTML:
<body>
<div class="nav_container">
<nav class="nav_main">
<div class="logo">
<a href="#">
<img src="../majo.png" alt="logo">
</a>
</div>
<ul class="nav" id="nav">
<li>
Home
</li>
<li>
Consultas
<div id="nav_consul" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Informação Dia a Dia
</li>
<li>
Totais Mensais
</li>
<li>
Tarifário Atual da Rede
</li>
<li>
Data específica
</li>
<li>
Atividade do Sistema
</li>
<li>
Coimas
</li>
</ul>
</div>
</div>
</li>
<li>
Simulações
<div id="nav_simul" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Criar tarifa Simples
</li>
<li>
Criar tarifa Complexa
</li>
<li>
Simular com Nova Tarifa
</li>
</ul>
</div>
</div>
</li>
<li>
Preferências
<div id="nav_prefs" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Lista de acessos
</li>
<li>
Alterar Password
</li>
<li>
Alterar Dados de Conta
</li>
</ul>
</div>
</div>
</li>
<li>
Log Out
</li>
</ul>
</nav>
</div>
<div id="content_main">
</div>
<footer></footer>
<script src="../js/jQuery.js"></script>
<script src="../js/user_menu.js"></script>
<script src="../js/user_nav.js"></script>
<script src="../js/user_clear_sub_menu.js"></script>
</body>
Here is an easy solution:
Create the following CSS-Styles:
.nav_content.visible {
max-height: 400px;
}
.nav_content.invisible {
max-height: 0px;
}
Set the overflow property for your nav_content to hidden:
.nav_content{
overflow: hidden;
}
Now add the class invisible to your submenus, if you want them to be invisible by default (you can do this manually in the markup or by js code):
Manually e.g.:
<div id="nav_prefs" class="nav_content invisible">
or by code (after the elements have been loaded):
$(".nav_content").addClass("invisible);
Now, if you just need to adjust your drop_down function to toggle the element's invisible/visible class:
function drop_down(dropdownID){
$('#'+dropdownID).toggleClass("visible invisible");
}
UPDATE: To make all visible submenus disappear when clicked elsewhere use this piece of code, when the window is loaded:
$(document).on('click', function (e) {
if (!$(e.target).is('.nav_item') && !$(".nav_item").has(e.target).length !== 0) {
$('.nav_content.visible').toggleClass("visible invisible");
}
});
If you only want to have one submenu visible at a time, you can use this version of your drop_down function:
function drop_down(dropdownID) {
$('.nav_content.visible').toggleClass("visible invisible");
$('#' + dropdownID).toggleClass("visible invisible");
}
A working fiddle can be found here
EDIT: Since you used jQuery in your original code, I assumed the answer can use jQuery too
You'll want to create a click handler on your document, then check the target of the click. If the target of the click has a certain class, use the menu behavior. If not, or if it's a sub-menu, close the menu.
Here's a question with multiple examples:
How do I close menu on click and when the user clicks away?
Also, I'd recommend not using max-height to hide and show. Since you're using jquery already, you could just use hide() and show().
One more thing: since you're using jquery already, you don't need to use these calls: document.getElementById(name). You can do a $("#yourId") or for document.getElementsByClassName("nav_content"); you can use $(".your-class")
It looks like you attached click event to entire document. I think you need to change only $('html').click(function() { to something like $('sub-menu-selector').click(function() { to
only activate the second function after I clicked my sub-menu
Aside to that, since it's only piece of jQuery and if you're not using it elsewhere, I would replace this with addEventListener and attachEvent, but maybe that's just me :)
In that case you can use jQuery.not() method to exclude the dropdown menu from your jQuery selection, here's what you need :
$('html').not(document.getElementsByClassName("nav_container")[0]).click(function() {
//As you can pass an element to it
You can also use the :not in your first selector like this:
$('html:not(div.nav_container))

javaScript changing parent menu item when child item is active

I'm pretty new to the javaScript and it would be very helpful for me if somebody could be so glad to give me some directions how to perform that. I'm creating website in Joomla 3 and I need to stylize the menu in a way that when a child menu item is active the parent item should change the background colour. I included the .js link into the head of the index.php file of my template. But I'm struggling second day with the desired script.
Here is my HTML:
<ul class="gf-menu l1">
<li class="item128 parent">
<a class="item" href"services">Services<span class="border-fixer"></span>::after</a>
<div class="dropdown columns-1">
<div class="column col1">
<ul class="l2">
<li class ="item1"><a class="item" href="submenu-01">Submenu1</a></li>
<li class ="item2"><a class="item" href="submenu-02">Submenu2</a></li>
<li class ="item3"><a class="item" href="submenu-03">Submenu3</a></li>
</ul>
</div>
</div>
</li>
</ul>
And that's it my CSS for it:
.gf-menu .dropdown{
border: 1px solid transparent;
border-radius:0;
background-color:#a9a9a9;
padding:10% 0;
width:100%;
text-shadow:none;
font-size:85%;
}
.gf-menu.l1 li.item1.active.last {background-color:#abcf39;}
.gf-menu.l1 li.item2.active.last {background-color:#f39512;}
.gf-menu.l1 li.item3.active.last {background-color:#f16e68;}
If you click on the <li> element and want to affect the parent you can use the .parent() method to target the parent element. The question is which one do you want to target. If it's the div which contains the <ul> you will have to access the parent of a parent. For example if the <li> has a class item as you stated in your question, you can do
$('.item').on('click', function(){
var clickedLiElement = $(this);
var parentHoldingUl = clickedLiElement.parent().parent();
//now you can do whatever you want with both of them, for example
clickedLiElement.addClass('active');
parentHoldingUl.css('background-color', 'green');
});
Update based on comments:
A slightly shorter version, which does what you specified in the comments
$('.item').on('click', function(){
$(this).css('background-color', '#5512F3');
$(this).parent().parent().css('background-color', '#5512F3');
$(this).siblings().css('background-color', '#AB99D5');
});
This should turn the clicked LI element and it's parent DIV dark blue and the clicked elemnent's siblings light blue.

Onmouseover/out

Two issues I am having.
The mouseover function is very FAST and it's definitely not working properly. I made a separate function for the onmouseout state, but it didnt help.
The class changes properly, however it stays changed and doesn't go back to it's original class. It depends if the link is on the selected page. Any help would be GREATLY appreciated
JAVASCRIPT:
function changeRollover(rollover) {
var rollItems = document.getElementById(rollover);
var rollLinks = rollItems.getElementsByTagName('a');
var noOfLinks = rollLinks.length;
for (var r = 0; r < noOfLinks; r++) {
var normalText = rollLinks[r].innerHTML;
var rolloverText = rollLinks[r].title;
var rolloverItem = document.getElementById(rollover);
rolloverItem.innerHTML = "<a href='#' title='" + normalText + "'>" + rolloverText + "</a>";
rolloverItem.class = rollover + "rollover";
}
}
HTML:
<div class="nav">
<ul id="NavItems">
<li id="item0" class="selected" onClick="changeClass(this.id)"
onmouseover="changeRollover(this.id)">
Collections
</li>
<li id="item1" onClick="changeClass(this.id)"
onmouseover="changeRollover(this.id)">
<a href="#" title="Shop Everything" >All Jewlery</a>
</li>
<li id="item2" onmouseover="changeRollover(this.id)"
onClick="changeClass(this.id)">
As Seen On
</li>
<li id="item3" onmouseover="changeRollover(this.id)"
onClick="changeClass(this.id)">
Collaborations
</li>
<li id="item4" onmouseover="changeRollover(this.id)"
onClick="changeClass(this.id)">
Designer Pop Ups
</li>
</ul>
<div class="shipping">
<a href="#">start your free orders today<br>
*** click here for more information ***</a>
</div>
</div>
<!-- .nav -->
The effect you want (dubious from a usability perspective, but that aside) is better achieved using some simple CSS:
#NavItems .hover {
display: none;
}
#NavItems:hover .hover {
display: inline;
}
#NavItems:hover .normal {
display: none;
}
Which requires markup like this:
<ul id="NavItems">
<li id="item0">
<a href="#">
<span class="normal">Collections</span><span class="hover">Shop Trends</span>
</a>
</li>
</ul>
Depending on your browser compatability requirements, I'd recommend using onmouseenter instead as the trigger for your function.
DOM Events - Browser Compatability
But for one thing, you're missing an onmouseout function that can reset the class for you. Once you attach a class to an element, it has to be removed manually as well if you want it to go away depending on what the user does. So create something like a resetRollover function, like the one below, and attach an onmouseout DOM listener that fires that function:
function resetRollover(rollover) {
var className = document.getElementById(rollover).className;
document.getElementById(rollover).className = className.substring(0, indexOf(' rollover'));
}
The problem is your onmouseover handler is on the lis. When the mouse hovers over the <a>s in the <li> and "reenters" onmouseover of the <li> is triggered again.
Example here: this is the same code as yours, I added some colors. If you move the mouse only on the black part (the <li>), the rollover happens as desired. But when you move the mouse on the green part (the <a>s).
As a solution, you can either handle the rollover on the <a>s or change your basic design (see #Thomas' answer)

Categories