Jquery conditional statement? - javascript

I'm trying to wrote my script for onepageweb nav. Main goal was to change selector on click and first part is working fine but first li is site logo so when I click on logo I want add .select second li. :
$(document).ready(function (){
$(".main-nav li").click(function () {
if (this = $(".main-nav li:first-of-type")) {
$(this).next().addClass("selected")
.siblings().removeClass("selected");
} else {
$(this).addClass("selected")
.siblings().removeClass("selected");
}
});
});
and this condition not work

Two problems:
You're using = for comparison (if (this = $(".main-nav li:first-of-type"))). = is always assignment. Since you can't assign to this, that's an error and nothing else will happen.
If you were using == or === there, it wouldn't work, because this will refer to a DOM element, but the return value of $() is always a jQuery object.
You may want
if ($(this).is(".main-nav li:first-of-type"))
...which uses is to test if the clicked element matches the given selector.
Side note: :first-of-type should work, but because ul elements can only contain li elements, :first would work as well.
Live Example:
$(document).ready(function() {
$(".main-nav li").click(function() {
if ($(this).is(".main-nav li:first-of-type")) {
$(this).next().addClass("selected")
.siblings().removeClass("selected");
} else {
$(this).addClass("selected")
.siblings().removeClass("selected");
}
});
});
.selected {
color: red;
}
<ul class="main-nav">
<li>The logo item</li>
<li>The second item</li>
<li>The third item</li>
<ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Related

do something when an instance becomes true in an each() function

I am running jQuery's .each function on a button click that runs through three line items. When another object on the page is clicked one of the line items will receive a class of 'selected', it starts on the first line item as default.
I want to execute something when the data-index of the li is greater than 0 and that li has the class name of selected.
const $orderStatusButton = $('form#oar-widget-orders-and-returns-form button');
$orderStatusButton.on('click', function() {
$(".selectric-scroll ul li").each(function() {
var DataIndex = $(this).data('index');
console.log(DataIndex);
if ((DataIndex > 0) && ($(this).hasClass('selected'))) {
$('div#oar_select-error').css('display', 'none');
} else {
$('div#oar_select-error').css('display', 'block');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-index="0" class="selected"></li>
<li data-index="1" class=""></li>
<li data-index="2" class=""></li>
</ul>
Essentially, I want to hide a div when the line item with the data-index of 1 or 2 has the class name of selected and show it when the line item with the data-index of 0 has the class name selected and I'm not sure if I'm going about this correctly as it isn't working.
Since you are looping through all elements you'll always end up with the display value of the last iteration of the each function.
What you should probably be doing is using the selected class on your jquery selector:
$(".selectric-scroll ul li.selected")
then you only have to process one element on the each function.
Why not just use toggleClass("someclass") and add CSS
li.someclass {
display:none;
OR
visibility:hidden;
};

Find if current class contains word, then append new class to those li's - jquery

Having some problems with jQuery methods - perhaps overcomplicating things...
What I need to find is if any of the li elements classes contain the word 'current', then if they do, append the word active to them.
I'm struggling to add the word to the end of the current class. For example:
Markup:
<div class="menu-navigation-container">
<ul>
<li class="current_page_item menu-item-8787"><span>The Magazine</span>
</li>
<li class="menu-item menu-item-type-post_type"><span>Snapped</span>
</li>
</ul>
</div>
jQuery:
$(document).ready(function () {
var classNames = $('.menu-navigation-container ul li').attr("class").match(/[\w-]*current[\w-]*/g);
$(classNames).each(function () {
$(this).addClass("active");
});
});
Running classnames; up in the console produces just the string - I want it to reference the li elemens that have the word 'current' in their class names, then append the word 'active' at the end.
Can I do this with jQuery's attribute contains selector?
Simply like this :
$(document).ready(function () {
$('.menu-navigation-container ul li[class*=current]').addClass('active');
});
Try this
$(document).ready(function () {
$('.menu-navigation-container ul li').each(function(){
if ( $(this).is(".current") )
{
$(this).addClass("active");
}
})
});

Get updated order after jQuery Sort

I am using jQuery UI's Sortable to reorder some list items. I would like to update the class of each li based on the updated order after sorting. Here is my html:
<ul id="sortable">
<li class="1">apple</li>
<li class="2">orange</li>
<li class="3">pear</li>
<li class="4">peach</li>
</ul>
What I am trying to achieve is AFTER sorting pear above apple, my classes update like this:
<ul id="sortable">
<li class="1">pear</li>
<li class="2">apple</li>
<li class="3">orange</li>
<li class="4">peach</li>
</ul>
This JSFiddle is close to what I'm after, but I would like to update the class rather than the html: http://jsfiddle.net/4mcpq/3/
As changing the position of one li would change the class of every other li, the only sane way to accomplish this is to iterate over the li elements on the update callback for .sortable:
"update": function (event, ui) {
$(this).children().each(function (i, elem) {
var li = $(elem), // cache lookup
cssClass = elem.className.split(' ').filter(function (name, i, array) {
return /^js[-]\d+$/g.test(name);
}).join(''); // adding .join('') to transform to string
// classes cannot start with a number (see http://www.w3.org/TR/CSS21/grammar.html#scanner).
// using pattern of "js-#" for the custom class
$(elem).removeClass(cssClass).addClass('js-' + i);
});
}
Working demo: http://jsfiddle.net/4mcpq/210/
A caveat: if you have thousands of li elements, this will likely slow your UI. There are much easier (and saner) ways to get the correct target li depending on what you're trying to do.
Why not use something like nth-child() selector in your css.
For example:
#sortable li:nth-child(1) {
/*insert your style for the first child here*/
}
#sortable li:nth-child(2) {
/*insert your style for the second child here*/
}
So I have found I can use .index() to find the updated sort order. Then I can set the class of each li to it's index.
$("#sortable").sortable({
update: function(event, ui) {
$("#sortable li").each(function() {
$(this).removeClass();
var $index = $(this).index();
$(this).prop("class", $index);
});
}
});
See this Fiddle: http://jsfiddle.net/2f9vkhxj/8/

Cant get the value of <li data-*> element. Tried Javascript as well as Jquery

The following is my dropdown list.
<ul id="navBar" data-value="">
<li data-city-value="blore">Bangalore
<ul>
<li data-city-value="delhi">Delhi</li>
<li data-city-value="che">Chennai</li>
<li data-city-value="jaipur">Jaipur</li>
<li data-city-value="hyd">Hyderabad</li>
<li data-city-value="mum">Mumbai</li>
<li data-city-value="pune">Pune</li>
</ul>
</li>
</ul>
And the following are my methods I tried to access the data-city-value attribute.
Method 1)
var cityName = document.getElementById('navBar');
var city = cityName.getAttribute('data-city-value');
alert(city);
It alerts "null"
Method 2)
var cityName = document.getElementById('navBar');
var city = cityName.dataset.cityValue;
alert(city);
It alerts "undefined".
Method 3)
$('#navBar li').click(function() {
$(this).parent().data('value', $(this).data('cityValue'));
});
alert($('#city').data('value'));
It alerts "undefined".
I checked the syntax to get data value here
It would be of great help if you can help me find where I am doing mistake.
Thanks. :)
IN your first two methods you target the top ul with id navBar. In the third method you do $(this).parent() which again takes you to the ul element.
That element does not have the data-city-value attribute.
The jquery method should be
$('#navBar').on('click','li', function(e) {
var city = $(this).data('city-value');
alert(city);
return false;
});
Demo at http://jsfiddle.net/gaby/Mb7KS/
As pointed out by Gaby, you need to reach the element firts. Try this:
$('#navBar:first-child')
This is how you can iterate through your data-city-value attributes:
$('li[data-city-value]').each(function(index,element){
alert($(element).data('city-value'));
});
You can also check my jsFiddle example.
For click events:
$(document).ready(function()
{
$('li').click(function() {
alert($(this).data('city-value'));
return false;
});
});
You should return false because the top li element has inner elements and it was triggering inner li element click event.
My second jsFiddle demo.

Determine if element has children with X tag

I am looping through some elements and need to determine if an element has a child(grandchild?) with the li tag, like in the information element below. The li elements will vary in id so I am not referencing them that way. I am currently looping through the li elements and if I check for children it always returns true because there are "a" tag children, I just want to check for 'lil' tag children.
<ul id="navMenu">
<li id="home">Home</li>
<li id="information">Information
<ul>
<li>Credits</li>
<li>Lorem Ipsum</li>
</ul>
</li>
<li id="contact">Contact</li>
</ul>
Here is what I have now...
$('#test').load('../common.html #navMenu', function() {
$.each($("#test #navMenu li"), function(i,v) {
var theElement = $(v);
if ($(theElement).children('li')){
alert('This Element has children');
}
});
});
Thank you once again,
Todd
You could try -
$('#test').load('../common.html #navMenu', function() {
$.each($("#test #navMenu li"), function(i,v) {
var theElement = $(v);
if ($(theElement).find('li').length > 0){
alert('This Element has children');
}
});
});
find will go deeper into the current element than children which only searches one level down.
$(theElement).children('li') returns a jQuery object which always passes an if clause, even when it's empty.
Moreover, you want .find, since .children only returns direct children and not grandchildren.
So:
if ($(theElement).find('li').length > 0) {
or:
if ($(theElement).find('li').length) {
// 0 won't pass an if clause, and all other numbers will, so you can eliminate `> 0`
Given:
> var theElement = $(v);
> if ($(theElement).children('li')) {
> alert('This Element has children');
> }
doesn't $(v) return an jQuery object? So $(theElement) is redundant.
Anyhow, if v is a reference to one of the elements passed to .each, then you can replace all of the above with:
if (v.getElementsByTagName('li').length) {
/* v has li descendants */
]
you could also add the extra li to your query: "#test #navMenu li li"

Categories

Resources