I am currently developing a program. It includes a 3 option navigation bar. It uses <li> and does not have id's, when i try to add id's to them it messes up the order, and doesent even work with a click! Im starting to loose faith with it.. can anyone help me on this one,
my GOAL is to have it alert different things on different clicks, so than I could link different html pages,
fiddle used HERE.
<ul class="ui-module menu-selector" id="menu-selector">
<li>Home</li>
<li class="js-is-active">Notif's</li>
<li>Profile</li>
</ul>
Since you don't have ids, I suppose that childNodes property will help a lot.
For example, you can use:
var lis = document.getElementById('menu-selector').childNodes;
// or you can select lis directly...
// var lis = document.querySelectorAll('#menu-selector li');
Array.prototype.slice.call(lis)
.forEach(function(li) {
// do something... like
li.onclick = function () {
console.log(this);
}
});
Note: childNodes (or querySelectorAll return) is NodeList type, and I use Array.prototype.slice.call() in order to use forEach() method on it.
See childNodes for more details.
if you don't want to have ids on your li elements for some reason you can use the following logic to select active li:
$("#menu-selector li.active").on("click", function(){
alert($(this).text())
});
I added id's for you, not sure what you meant by it messing up the order.
HTML
<div class="ui-items">
<header class="ui-module app-header">VoiceBox <i class="entypo-user-add"></i>
<i class="entypo-pencil"></i>
</header>
<div id="outer">
<ul class="ui-module menu-selector" id="menu-selector">
<li id="home_li">Home</li>
<li id="notif_li" class="js-is-active">Notif's</li>
<li id="profile_li">Profile</li>
</ul>
</div>
</div>
Javascript
var listItem = $('#menu-selector > li');
$(listItem).click(function() {
$(listItem).removeClass('js-is-active');
$(this).toggleClass('js-is-active');
});
$('#home_li').click(function(){
alert('home clicked')
})
$('#notif_li').click(function(){
alert('notifs clicked')
})
$('#profile_li').click(function(){
alert('profile clicked')
})
Fiddle http://jsfiddle.net/1swep9oq/2/
Related
I'm new to jquery, ajax and jstree. I'm using jstree to have my <ul> elements look like a tree structure.
I have the <ul> under a div tag of id = "container". When I execute the html file, the div (id = "container") is passed to jstree function as follows:
$(function() {
$('#container').jstree();
});
My html snippet is as follows:
<div id="container">
<ul id = "treeNodes">
<li>Parent
<ul>
<li>Child1
<ul>
<li>child2-1</li>
<li>child2-2</li>
<li>child2-3</li>
<li>child2-4</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
The tree structure is being displayed fine.
I'm trying to write a jquery function that gets the li element's name as an argument.
For example: when I click Parent, the function should recieve "Parent" as an argument or when I click child2-3, the function should get "child2-3" as the argument.
I attempted to create that function, but it doesn't seem to work. Here's my attempt -
$("#treeNodes li").click(function() {
console.log("hello");
console.log(this.innerHTML);
});
The control seems to go to the function calling the jstree(), but the other function doesn't seem to work.
Any help or tips would be appreciated. Thanks in advance.
Making your structure into a JSTree causes new HTML to be created and those new elements have custom classes and new APIs. So, you have to read the documentation to understand how to use the new structure.
If you look at this documentation page, you'll see an example of what you are after, which hinges on a custom changed event. I've reproduced that example, customizing it for your HTML and console output.
$(function() {
$('#container')
// listen for the custom "changed" event on any jstree
.on('changed.jstree', function (e, data) {
// When you click on a JSTree the event appears to fire on the entire tree
// You'll have to iterate the tree nodes for the selected one.
var i, j, r = [];
for(i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
}
console.clear();
console.log('Selected: ' + r.join(', '));
})
// create the instance
.jstree();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<div id="container">
<ul id = "treeNodes">
<li>Parent
<ul>
<li>Child1
<ul>
<li>child2-1</li>
<li>child2-2</li>
<li>child2-3</li>
<li>child2-4</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
I have read the documentation from the jstree page: https://www.jstree.com/
There is a class from the jstree called jstree-children, from that class you can obtain the value from the list, like this:
$(document).on('click', '.jstree-children ul li', function (e) {
console.log($(this).html());
});
Try this: https://jsfiddle.net/Mantixd/0jwpz2r1/
i have some code below:
<ul class="history">
<li class="hello"></li>
<li class="hi"></li>
<li class="yello"></li>
<div class="baby"></div>
<div class="kitty"></div>
</ul>
now i want remove some elements in ul, but i want hold 1 div or li (ex: div.baby) how can i do now? i want use click function.
with jQuery:
var babyElement = $('.baby') // save element for later
$('.yellow').remove() // remove element
with JavaScript:
var babyElement = document.querySelector('.baby')
var yellowElement = document.querySelector('.yellow')
if (yellowElement.parentNode) {
yellowElement.parentNode.removeChild(yellowElement)
}
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
maybe this is you want:
$('ul.history').children().not('.baby').remove();
demo
Suppose I have a List like the following
<ul>
<li id="slide-a" class="slide-li active-slide"><a href="#" >A</a></li>
<li id="slide-b" class="slide-li"><a href="#" >B</a></li>
<li id="slide-c" class="slide-li"><a href="#" >C</a></li
</ul>
Now , using Jquery I wanna Find out which Element has the class 'active-class'. One way would to have a nested if statement something like this:
if($("#slide-a").hasClass('active-slide'))
{
active = 'slide-a';
}
else
{
if($("#slide-b").hasClass('active-slide'))
{
active = 'slide-b';
}
else
{
if($("#slide-c").hasClass('active-slide'))
{
active = 'slide-c';
}
}
}
My question is if there exists any way to optimize the code above. Is there a generic way to achieve this such that even if I add 10 more li's in the ul the code just works fine without any modification.
Maybe just
var active = $(".active-slide").attr("id");
Demo
Use Attribute starts with selector and .each(). Try this:
$(document).ready(function(){
$('li[id^=slide]').each(function(){
if($(this).hasClass('active-slide'))
alert($(this).attr('id'));
});
});
DEMO
If you have more than one li with classactive-slide use this:
$(document).ready(function(){
var idVal = [];
$('li[id^=slide]').each(function(){
if($(this).hasClass('active-slide'))
idVal.push($(this).attr('id'));
});
console.log(idVal);
});
DEMO
You could a use jQuery $.each() on the ul to iterate through.
fiddle coming in a second.
I've read many tutorials and can't seem to get it right. Ok I know that the jquery click function works when you are doing something to the exact same element but how do you make it effect another and toggle back?
I have a menu and when I click on an item I want the background (body) to change to an image.
Example:
HTML
<body>
<ul class="menu">
<li class="menu-item"><a>item 1</a></li>
<li class="menu-item"><a>item 2</a></li>
<li class="menu-item"><a>item 3</a></li>
</ul>
</body>
JQUERY
$(".menu-item a").click(function () {
$(body).css('background', 'http://example.com/image.png'); <-- first menu item
$(body).css('background', 'http://example.com/image.png'); <-- second menu item
$(body).css('background', 'http://example.com/image.png'); <-- third menu item
});
You can use .index() - DEMO
$("a").on("click", function(e) {
e.preventDefault();
var i = $("li").index( $(this).parent() );
if ( i === 1 ) {
$('body').css('background', 'beige');
} else if ( i === 2 ) {
$('body').css('background', 'honeydew');
} else {
$('body').css('background', 'pink');
}
});
Does this seem about like what you're trying to do?
$(".menu-item a:nth-child(1)").click(function () { // first menu item
$(body).css('background', 'http://example.com/image.png');
});
$(".menu-item a:nth-child(2)").click(function () { // second menu item
$(body).css('background', 'http://example.com/image.png');
});
$(".menu-item a:nth-child(3)").click(function () { // third menu item
$(body).css('background', 'http://example.com/image.png');
});
I don't know what you are trying but I could give you hints.
$(".menu-item a") // is an array/jquery collection of all elements that match the selector
.click(function () { // binds the function now to the click event of every item found
$(this); // is now the currently clicked element
// you can now traversal with $(this) for example
$(this).siblings(); // will be a collection of all surrounding elements
$(this).next(); // is the next element after the current one, can be chained like:
$(this).next().next(); // but I wouldn't recomand
$(this).prev(); // same as next but prev
$(this).parent(); // selects the direct parent element, in your case the li element
$(this).children(); // would select the direct children of the current element
// and so on.... there are much more possibilities
// on every of this possibilities you can do your background change
$("some selector"); // is of course still possible
// i think you are trying to do this:
var menuItems = $(".menu-item a");
menuItems.eq(0).css("background", "url to bg 1");
menuItems.eq(1).css("background", "url to bg 2");
menuItems.eq(2).css("background", "url to bg 3");
})
Look at the Traversing section of the jQuery docu. I would also always recommend to look what jQuery is actually doing. Many people hide behind jQuerys api and have no idea whats happening. This results into many misunderstandings.
You may try something like this
HTML:
<body>
<ul class="menu">
<li class="menu-item"><a name="blue" href="#">item 1</a></li>
<li class="menu-item"><a name="red" href="#">item 2</a></li>
<li class="menu-item"><a name="orange" href="#">item 3</a></li>
</ul>
</body>
CSS:
.red {
background:red;
}
.blue {
background:blue;
}
.orange {
background:orange;
}
Jquery:
$('.menu').on('click', 'a', function () {
var bgColor = $(this).attr('name');
$('body').removeClass().addClass(bgColor);
return false;
});
DEMO
The way I suggest going about this is to grab the position of the element that has been clicked. You can do this by using jQuery's index() function as other posters have suggested. Remember this will give you a zero-based index of the position which means that the position counting starts at 0 as opposed to 1.
Based on the item that has been clicked, you assign a CSS class to the target item which is the body element based on the sample code you provided.
Also, I noticed that your JS comments are still invalid even they were edited. Single line comments in JS use a double forward slash, // whereas multiline comments begin with /* and are closed by */.
This is my solution: http://jsfiddle.net/tgZUK/.
My DOM looks something like this:
<li>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</li>
When the used clicks on 'Edit', I want to change the outer <li> to <li class="selected>.
I tried something like this, but this is not working:
$('li a.editEntity').live('click', function() {
$(this).closest('li').closest('li').addClass('selected');
});
Any help is appreciated.
Go up a parent:
$(this).closest('li').parent().closest('li').addClass('selected');
It wasn't working because closest starts with the current element, and so if you call it on something that matches the selector, you get back the same thing you started with.
Live example
Or you can use parents with the :eq selector:
$(this).parents("li:eq(1)").toggleClass("selected");
Note that :eq uses 0-based indexes, so :eq(1) is the second parent li.
Live example
Your quoted HTML is invalid, though (an li can't directly contain an li); I assume you meant:
<li>
<ul>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</ul>
</li>
...or similar.
you can use
$('li a.editEntity').live('click', function() {
$(this).parents('li').addClass('selected');
});
following my previous comment.. here's the example promised... :)
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
Stop at the second index
Further info can be found here
http://api.jquery.com/each/
I'm using this code to add active class depending on the page. This is working 100% for multi level sub-menus of AdminLTE 3, just put this code in the footer section of your page.
var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
return e.href == url;
});
currentLink[0].classList.add("active");
currentLink[0].closest(".nav-treeview").style.display = "block ";
currentLink[0].closest("ul.nav-treeview").closest('li').classList.add('menu-open');
$('.menu-open').find('a').each(function() {
if (!$(this).parents().hasClass('active')) {
$(this).parents().addClass("active");
$(this).addClass("active");
}
});