jQuery - Building a tree style list - javascript

My DOM is as follows
<ul>
<li id="Browse">
Browse
<ul id="browse-one">
</ul>
</li>
</ul>
My jQuery in a in the bottom of the page is:
$("#Browse").click(function() {
$("#browse-one").html('<div class="ui-widget">Loading...</div>');
$("#browse-one").load('../api/browse.php?do=getFirst');
});
This script goes into the database and spits out raw LIs. After this runs the DOM is modified as follows
<ul>
<li id="Browse">
Browse
<ul id="browse-one">
<li id="one-1" data-id="1">SOMETHING</li>
<li id="one-2" data-id="2">SOMETHING</li>
<li id="one-3" data-id="3">SOMETHING</li>
<li id="one-4" data-id="4">SOMETHING</li>
.
.
.
<li id="one-N" data-id="N">SOMETHING</li>
</ul>
</li>
</ul>
What is the proper jqueryish way to track clicks on these LIs. I want to extract the data-id of the clicked element and make a second API call to construct part two of the tree. For example if data-id="1"'s LI is clicked the DOM should be:
<ul>
<li id="Browse">
Browse
<ul id="browse-one">
<li id="one-1" data-id="1">SOMETHING
<ul id="Something Here">
<li id="two-1" data-id="1">HMM</li>
<li id="two-2" data-id="2">HMM</li>
<li id="two-3" data-id="3">HMM</li>
.
.
.
<li id="two-M" data-id="M">HMM</li>
</ul>
</li>
<li id="one-2" data-id="2">SOMETHING</li>
<li id="one-3" data-id="3">SOMETHING</li>
<li id="one-4" data-id="4">SOMETHING</li>
.
.
.
<li id="one-N" data-id="N">SOMETHING</li>
</ul>
</li>
</ul>
Im having trouble thinking of how i'de keep each of the inner UL's IDs unique. Sure I can do the "LEVEL-ID" as in "two-1" but I feel this is hackish and not the proper jquery way.
EDIT:
But now how do I track the children's clicks?? This doesn't seem valid but I hope you understand wht I'm trying to do
$("#Browse").click(function() {
$("#locations-browse").html('<div class="ui-widget">Loading...</div>');
$("#locations-browse").load('../api/browse.php?do=getFirst');
//Child is tracked
$("#locations-browse").delegate("li","click",function(evt){
var inner = $(this).append("<ul></ul>");
inner.html('<div class="ui-widget">Loading...</div>');
inner.load('../api/browse.php?do=getSecond');
$(this).delegate("li","click", function(evt) {
alert("Child ". $(this).data("id") . " is clicked";
});
});
});
EDIT 2:
Hmm this still is not working:
$("#Browse").click(function() {
$("#locations-browse").html('<div class="ui-widget">Loading...</div>');
$("#locations-browse").load('../api/browse.php?do=getFirst');
//Child is tracked
$("#locations-browse").delegate("li","click",function(evt){
$(this).append("<ul></ul>");
$(this).children("ul").load('../api/browse.php?do=getSecond?location-id='.$(this).data("id"));
$(this).delegate("li","click", function(evt) {
alert($(this).data("id"));
});
});
});

Delegate the event via li#Browse and reference the data-id attribute relative to the event's contextual element.
$('#Browse').on('click', 'li', function(evt) {
alert($(this).data('id'));
});
Incidentally, there's several out-of-the-box plugins that do what you need, just in case you didn't want to build you own, e.g. YUI Treeview or the one I wrote.

Related

How to target a specific element from a group of them having the same class/id in javascript?

I want to copy the text in the <li> tag using JavaScript. It should be copied when the <li> tag is clicked. All <li> tags have the same class as they will get the same formatting through CSS.
As per my research, we need to specify the button a target class which it will copy to clipboard(Using clipboard.js). The <li> tag will be generated through js so, to give different id to each one of them will be difficult and will increase the code and reduce the speed too.
So how can copy the text of the li tag that is being clicked through js/jquery/clipboard.js etc.
<ul>
<li class="data">Lorem ipdolor.</li>
<li class="data">Lo ripsum dolor.</li>
<li class="data">Lorepsum dor.</li>
</ul>
There are different methods but two that stand up on top.
$(function() {
$("li[class='data']").click(function(e) {
// 1) Use this reference
console.log("1: " + $(this).text());
// 2) Use Event Target
console.log("2: " + $(e.target).text());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="data">Lorem ipdolor.</li>
<li class="data">Lo ripsum dolor.</li>
<li class="data">Lorepsum dor.</li>
</ul>
You can put an id on ul:
<ul id="dataContainer">
<li class="data">sometext</li>
<li class="data">sometext1</li>
<li class="data">sometext2</li>
<li class="data">sometext3</li>
</ul>
Then:
document.getElementById('dataContainer').addEventListener('click', function(e){
console.log(e.target.innerText);
});

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');
});

To add class="current" Dynamically

I have Menu list which contains Sub-Menu as shown in the code below.
<li class="current">
<span class="icon4"></span>Subscriptions
<ul class="sub-menu">
<li>View Subscriptions
</li>
<li class="#((ViewBag.PageName == " Subscription ") ? "active " : " ")">Manage Subscription Plans
</li>
</ul>
</li>
<li class="current">
<span class="icon5"></span>Administration
<ul class="sub-menu">
<li class="#((ViewBag.PageName == " AssetPage ") ? "active " : " ")">Assets
</li>
<li>Configure Text
</li>
<li>Error Log
</li>
<li>Product Settings
</li>
</ul>
</li>
<li class="current">
<span class="icon6"></span>Promo Codes
<ul class="sub-menu">
<li>Manage Promo Code
</li>
<li>Used Promo Code
</li>
</ul>
</li>
Here Subscription,Administration,Promo Codes are Menu Lists which contains Sub-Menu Lists under them.
The thing is I want to apply class=current dynamically when a user clicks on Subscription,Administration,Promo Codes`.
And I am doing this in LayoutPage of MVC.
Any help will be appreciated.
Here you have a working solution: https://jsfiddle.net/c4h3sup9/
You have to use a little bit of Javascript for that.
You have to give the listitems a other class name like in my example "operator"
document.body.addEventListener("click", function(e){
if(e.target && e.target.className == "operator"){
var actives = document.getElementsByClassName("active");
actives[0].setAttribute("class", "operator");
e.target.setAttribute("class", "active");
}
});
for this example you need to assing one element as active from the beginning.
Note:
LI elements are never parents of UL.
The order is:
Unordered List (Plural) -> List item (Singular, Child).
You might want to correct that as it is not standard conform.
To add the class name to the parent <li> element, give the main links a class name. Assuming you also want to remove it from any <li> elements that already have it, also give them a class name
<li class="container">
<span class="icon4"></span>Subscriptions
and the script will be
$('.mainmenu').click(function() {
$('.container').removeClass('current'); // remove any previous
$(this).closest('.container').addClass('current');
});
In addition, if when you navigate to one of the views with this layout, and what to add the class name to the appropriate element, then you can give the <li> elements an id attribute
<li id="subscriptions" class="container">
....
</li>
<li id="administration" class="container">
....
and in the GET method, pass the value of the id to the view (e.g. using ViewBag
public ActionResult ConfigureText()
{
ViewBag.Menu = "administration";
....
return View(...);
}
and add a script that runs when the page first loads
var menu = '#ViewBag.Menu";
$('#' + menu).addClass('current');

Matching the URL path with <a> attr('href') to dynamically update .active class

Hey guys i have my navbar code in a navbar.php file and the HTML looks like as follows :
<nav role="navigation" class="nav" >
<ul class="menu" id="menu">
<li class="active"><a href="index.php">
Home</a></li>
<li>About us</li>
<li>Products
<ul class="submenu">
<li class="active">product-1</li>
<li>product-2</li>
<li>product-3</li>
<li>product-4</li>
<li>product-5</li>
<li>product-6</li>
</ul>
</li>
<li>Contact us</li>
</ul>
</nav>
onpage load i am running a very simple Jquery snippet to run through all the <a> and check if thier href matches the url (actually end of the url eg. index.php ) in the browser .
So i have the following Jquery snippet :
$(document).ready(function(){
var _urlpath = $(location).attr('pathname');
console.log(_urlpath); // this does't print out the desired version , it prints `/lala-v1/about-us.php"`
$('#menu > li').each(function(){
var _str = $(this).find('a').attr('href');
console.log(_str); // these print out the desired output eg. index.php
if(_str == _urlpath){
console.log(_str + _urlpath);
}
});
});
checkout my comments and , my difficulty is getting the correct url path on the 2nd line of on Jquery . I went through this article and none of of the Jquery options i see are going to return the end part of the URL i see .
so what do i do ? i am stuck , is there a way around this in JS/Jquery .
I am new to both these feilds , so i would appreciate any help .
Try this:
var _urlpath = window.location.pathname.split('/').pop();
// or: $(location).attr('pathname').split('/').pop();
Use prop() instead of attr() , it will return the absolute path, not the string that has been set for the attribute .
Comparing filenames may fail, there may be files with equal names in different directories.
$(document).ready(function(){
$('#menu > li').each(function(){
var _str = $(this).find('a').prop('href');
if(_str == location.href){
$(this).css('background','red');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu" id="menu">
<li class="active"><a href="index.html">
Home</a></li>
<li>About us</li>
<li>This is the current page, should be highlighted by jquery</li>
<li>Products
<ul class="submenu">
<li class="active">product-1</li>
<li>product-2</li>
<li>product-3</li>
<li>product-4</li>
<li>product-5</li>
<li>product-6</li>
</ul>
</li>
<li>Contact us</li>
</ul>
The values won't match, since /lala-v1/about-us.php !== about-us.html, plus you're serving pages with ".php" and links are all ".html". You can use this to get the correct value: window.location.pathname.split('/').pop();

Menu with ajax load not working properly

I create a menu with ajax load. I have 4 zones and each zone have states. What i want is on hover on zone, i need to display all states in that zone. I write following code
HTML
<ul class="zoneLevel">
<li id="1" onmouseover="get_states_list(this.id);">East Zone
<span id="stateContainer" style="display:none;">States</span>
</li>
<li id="2">West Zone</li>
<li id="3">North Zone</li>
<li id="4">South Zone</li>
</ul>
JAVASCRIPT
<script>
function get_states_list(zone_id) {
//alert(zone_id);
var last_slug_a1 = $(".homeLeftContainer .single:last").attr("id");
$('span#stateContainer').html('<img src="img/loader.gif">');
$.post("modules/frontend/ajax/load_state.php?action=get&zone_id="+zone_id,
function(data){
if (data != "") {
$("span#stateContainer").html(data);
}
});
$(".stateContainer").css("display", "block");
$(".stateHederMenu").css("display", "block");
}
</script>
everything's good.
Problem started when i mouse hover to state (which i get with ajax file), it again call get_states_list(this.id) function. Can you please point the error.
It's because again you are hovering the li, the actual span is inside the li and hence the function is triggered again. So just use another tag maybe <a>,<p>,<span> or anything after li and close the word. so it wont trigger again unless you mouse over to the word.
<ul class="zoneLevel">
<li id="1" >
<a onmouseover="get_states_list(this.id);">East Zone</a>
<span id="stateContainer" style="display:none;">
States
</span>
</li>
<li id="2">West Zone</li>
<li id="3">North Zone</li>
<li id="4">South Zone</li>
</ul>
Example with jQuery
$('.zoneLevel li').one('mouseover',function (){
get_states_list($(this).attr('id'));
})
And fiddle for this situation fiddle

Categories