Select random list item and add class - javascript

At the moment I have an unordered list with the id of menu and one list item within this ul has a class of "selected"
what i would like to do is grab all the list items from within the ul and remove the inital selected class from the list item it is on then assign it to a different list item within the same ul each time the page is refreshed.
Is this possible? Whats the best method to achieve this?

$(document).ready(function() {
var $ulLen = $('#menu li').length;
$('#menu li').removeClass('selected'); // Remove the class
// Select random li..
var rand = Math.floor( (Math.random()* $ulLen ) ); // Select a random li..
$('#menu li:eq('+ rand + ')').addClass('selected');
// Add the selected class to randomly selected li...
});
Check FIDDLE

http://jsfiddle.net/eWbqa/8/
var menu = document.getElementById('menu');
var tags = menu.getElementsByTagName('li');
tags[Math.floor(Math.random() * tags.length)].setAttribute('class', 'selected');
You could expand on that, but that will do it.
*Edited to reflect Naveen's good advice.

This could probably be written shorter, but I wanted it more verbose so you could see the steps. Technically this could pick the same one twice. If you wanted, you could use LocalStorage or a cookie to remember the last item and not select it again. I went for simple.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
//remove the selected class from the li that has it
$("li.selected").removeClass("selected");
//get all the LIs
var menuItems = $("ul#menu li");
//How many do we have?
var numItems = menuItems.length;
console.log(numItems);
//Pick one by randm
var selected = Math.floor(Math.random()*numItems);
console.log(selected);
//And set it
$("ul#menu li:nth-child("+(selected+1)+")").addClass("selected");
});
</script>
<style>
li.selected { background-color: red; }
</style>
</head>
<body>
<ul id="menu">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li class="selected">Item four</li>
<li>Item five</li>
</ul>
</body>
</html>

Related

How can I remove a child from another child in Javascript?

I'm trying to access a div in a li element, and then delete it. But I need to access it through another parenting div, which contains the li. My attempts at this have not worked. Here is what I have tried: parentDiv.childNodes[0].removeChild(document.getElementsById('removeThisChild').
Does anyone know how I could achieve this?
Thanks :)
Update
Here is the HTML code:
<head>
<script type="text/javascript">
window.onload = function() {
var ul = document.getElementById('ul')
ul.childNodes[0].removeChild(document.getElementById('div'))
}
</script>
</head>
<body>
<ul id="ul">
<li id="li">this is the LI text <div id='div'>this is the div text</div></li>
</ul>
</body>
</html>
I have made a code pen - http://codepen.io/dmoojunk/pen/dMVgzb
var child = document.querySelector('#li');
child.parentElement.querySelector('li > div').remove();

How to get the text of li without giving them ids?

I have four li tags inside a ul tag.
i want to get text inside li tag when i select one li and i want to hide the other three li values.
Only the selected one should still be shown on the page.
<ul id="names">
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
$('#names li').click(function(){
$(this).siblings().hide();
});
This answers both parts of your question:
$('#names li').click(function(){
var x = $(this).text(); // gets the text of the selected li
alert(x); // displays the text inside the selected li
$(this).siblings().hide();​​​​ // hides all other li's
});
Here is a working jsFiddle for your example.
How about this? It will hide them all and display the one which was clicked using a jQuery selector.
$('#names li').click(function() {
$('#names li').hide();
$(this).show();
})
Example of use: http://jsfiddle.net/eqUD3/
Try like this
$("#names li").click(function(){
var selected = $(this);
alert('You have selected '+ $(this).text());
$("#names li").hide();
$(this).show();
});
check the fiddle DEMO

jquery Current Nav item selector

I can't figure out how to use jQuery to style the current nav item. I've tried several tutorials and such to no avail. Any help would be appreciated.
Thanks in advance.
<div id="menu">
<ul id="nav">
<li>Contact</li>
<li>Gallery</li>
<li>Pool Liners</li>
<li>Services</li>
<li>About</li>
<li>Home</li>
</ul><!--end nav-->
</div><!--end menu-->
/** nav styling **/
//<![CDATA[
jQuery(function() {
jQuery('#nav li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).addClass('current');
}
});
});
//]]>
You can use the Attribute Equals Selector [name="value"] to find out the nav item with the current path.
$(document).ready(function () {
var str = location.href.toLowerCase();
var item = $('#nav li a[href="' + str + '"]');
if(item.length){
$("li.current").removeClass("current");
item.parent().addClass("current");
}
})
Demo: Fiddle
I figured it out!! Thanks for your help Will.i.am and Arun.p.
THe lines of code below is all I needed after giving body id's to each page.
/** nav selector **/
var bodyid = $('body').attr('id');
$('#main_nav ul li a.'+ bodyid).addClass('current');

Tweak drop down menu so top level stays highlighted

I am using this drop down menu code: http://javascript-array.com/scripts/jquery_simple_drop_down_menu/ and I am trying (with no success) to keep the top level highlighted even when the mouse moves down to the lower links on a dropdown menu.
The html:
<ul id="jsddm">
<li>JavaScript
<ul>
<li>Drop Down Menu</li>
<li>jQuery Plugin</li>
<li>Ajax Navigation</li>
</ul>
</li>
<li>Effect
<ul>
<li>Slide Effect</li>
<li>Fade Effect</li>
<li>Opacity Mode</li>
<li>Drop Shadow</li>
<li>Semitransparent</li>
</ul>
</li>
<li>Navigation</li>
<li>HTML/CSS</li>
<li>Help</li>
</ul>
The original Javascript:
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
function jsddm_open()
{ jsddm_canceltimer();
jsddm_close();
ddmenuitem = $(this).find('ul').css('visibility', 'visible');}
function jsddm_close()
{ if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}
function jsddm_timer()
{ closetimer = window.setTimeout(jsddm_close, timeout);}
function jsddm_canceltimer()
{ if(closetimer)
{ window.clearTimeout(closetimer);
closetimer = null;}}
$(document).ready(function()
{ $('#jsddm > li').bind('mouseover', jsddm_open)
$('#jsddm > li').bind('mouseout', jsddm_timer)});
document.onclick = jsddm_close;
P.S. Three cheers to the guy that wrote this, I love it, keeps my html super clean and easy to update.
Add
ul li:hover {
background:...
}
In your stylesheet and you should get the desired effect. because your submenu is nested within your list item - whilst hovering over your sub-menu you a still effectively hovering over its parent (list item) also.
You can keep the hover on ul li a - if you like but this won't keep your styles as the submenu is not nested within it.

Jquery: How to target the parent ul and count the li's held?

I am using jstree to build a tree menu.
When you select an item in the tree a div on the right brings up certain information. The information can be deleted.
When it is deleted I remove that item from the tree.
The problem is when the last li is removed from the ul, I need to remove the ul and also remove the "open" and "close" classes from the parent li and add the class "leaf".
I am having a hard time targeting the ul and in turn targeting the parent li as well.
I have to use the "clicked" class as a starting reference.
Here is the tree html:
<li id="447" class="open">
<ins> </ins>ZigBee Remote Pairing-D
<ul>
<li id="470" class="leaf last clicked">
<ins> </ins>RCA TV2 - Audio Quality-F
</li>
</ul>
</li>
here is the jquery:
var numLi = $(".clicked").parent("ul:first > li").size();//get number of li in ul
if (numLi == 1){
$(".clicked").parent("ul:first").parent("li:first").removeClass().addClass("leaf");
}
$(".clicked").parent("li:first").remove();//remove the list item from the tree
Something like this should work:
var clickedLi = $('.clicked').parent('li');
var parentUlOfClickedLi = clickedLi.parent('ul');
if (parentUlOfClickedLi.children('li').length === 1) {
parentUlOfClickedLi.parent('li')
.removeClass('open close')
.addClass('leaf');
}
clickedLi.remove();

Categories