I have list that has one active class element
<ul class="tabs clearfix" >
<li>
<a title="abc" href=# >ABC</a>
</li>
<li>
<a title="xyx" href=# >XYZ</a>
</li>
<li class=active >
<a title="all" href=# >All</a>
</li>
I am using local storage to store the title of a tag which is then used to loadcontent accordingly. I am having difficulty in getting the specific li element when i fetch the titel back from local storage. I would like to add an active class to li element that corresponds to the specific title. Here's the javascript code:
$(document).ready(function(){
var tabs = $('.tabs > li');
if (localStorage.getItem("tabIndex") === null) {
$( "#content" ).load( "{{url_for('mypage', query=query)}}" );
}else{
var lastIndex = localStorage.getItem('tabIndex');
**Do something to get the specific li element for the title**
**addclass('active') for the li**
LoadContent(lastIndex);
}
tabs.on("click", function(){
tabs.removeClass('active');
localStorage.setItem('tabIndex', $('a', this).attr('title'));
$(this).addClass('active');
var index = $(this).children('a')[0].title;
LoadContent(index);
})
});
I tried $("a[title=lastIndex]").parent().addClass('active'); but this doesnt seem to work. As always, I really appreciate all the help that this site provides me. Thanks
You can use $('a[title="'+ lastIndex +'"]') to get the desired element,
Eg: say your lastIndex = xyz then the selector becomes $('a[title="xyz"]')
Related
I want to pass which li is clicked. The clicked li number i have to pass through onclick function. There is no id is defined to any li.
Example is second li is clicked, i want to pass onclick="imageDisplayClick(2) but i am not able to get the count.
<div id="slider_text">
<ul onclick="imageDisplayClick()">
<li><h1 style="color:orange;">SPORTS & FITNESS</h1></li>
<li><h1>ACCU - CHEK Strips</h1></li>
<li><h1>NATURE'S BOUNTY</h1></li>
<li><h1>Beauty Care</h1></li>
</ul>
</div>
Please help me to solve this issue
For starters, I would not recommend using the onclick attribute, but rather making use of Unobtrusive JavaScript and separating it out to a function.
After separating out the logic, it's only a small extra step to loop over the elements, which can be acquired with .querySelectorAll.
From here you now have a click handler on each individual <li> element that can reference the element in question with the this keyword. Because you have access to the element directly, you shouldn't actually need to pass through the relevant offset into the function in question.
var points = document.querySelectorAll('#slider_text > ul > li');
for (var i = 0; i < points.length; i++) {
points[i].addEventListener('click', function() {
console.log(this.innerHTML);
})
}
<div id="slider_text">
<ul>
<li>
<h1 style="color:orange;">SPORTS & FITNESS</h1>
</li>
<li>
<h1>ACCU - CHEK Strips</h1>
</li>
<li>
<h1>NATURE'S BOUNTY</h1>
</li>
<li>
<h1>Beauty Care</h1>
</li>
</ul>
</div>
Hope this helps! :)
Use this, it will pass a reference to the DOM element itself.
<ul onclick="imageDisplayClick(this)">
You should consider using https://developer.mozilla.org/fr/docs/Web/API/EventTarget/addEventListener as it makes everything lie in your javascript file and prevents from having js fragments scattered in your html.
You can then use the event parameter to find out in detail what was clicked:
Test it here https://jsfiddle.net/jteLw8qa/
HTML:
<div id="slider_text">
<ul id="selection">
<!-- data-XXX can be accessed in javascript with element.dataset.XXX AS A STRING -->
<li data-yourdata="42"><h1 style="color:orange;">SPORTS & FITNESS</h1></li>
<li data-yourdata="elephant"><h1>ACCU - CHEK Strips</h1></li>
<li data-yourdata="pink"><h1>NATURE'S BOUNTY</h1></li>
<li data-yourdata="stackoverflow"><h1>Beauty Care</h1></li>
</ul>
</div>
JS:
function imageDisplayClick(event)
{
// find the clicked li element
var target = event.target;
// find first parent li or ul
while(target.tagName != 'LI' && target.tagName != 'UL')
target = target.parentNode;// because you have <h1> in your <li>
// if li is a parent the user clicked on it, else he clicked on the side but still on the ul
if(target.tagName == 'LI')
alert('clicked li with data-yourdata=' + target.dataset.yourdata);
}
// have the click event being listened on our ul#selection element
document.getElementById('selection').addEventListener('click', imageDisplayClick);
On top of the other answers provided, an event argument is also passed to the click handler, which should provide you with information on what specific thing was clicked on.
In your case, you could do something like this:
imageDisplayClick = function(event){
var target = event.target.tagName=="H1"?event.target.parentNode:event.target;
console.log(target);
}
<div id="slider_text">
<ul onclick="imageDisplayClick(event)">
<li><h1 style="color:orange;">SPORTS & FITNESS</h1></li>
<li><h1>ACCU - CHEK Strips</h1></li>
<li><h1>NATURE'S BOUNTY</h1></li>
<li><h1>Beauty Care</h1></li>
</ul>
</div>
I have the the following in my script tag. However, whenever I click the on test.php or test2.php li links, I am not redirected to the respective pages.
However, the active class changes from the index.php file to the test.php or test2.php file depending on which link has been clicked but I am not directed to the page. I attempted to the solutions in the following links, but now of them produce the desired result that I want, which is to redirect me to the page clicked and update the active class to the li element.
How to change active class while click to another link in bootstrap use jquery?
Active link after click
Whenever I uncomment this line e.preventDefault(), I am able to navigate to the link that have been click but the active class is not updated to the the
li elememnt clicked, but when the said line is commented, I am not able to navigate to the page clicked, instead, the active class is updated on the li element clicked.
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="active">
<a href="index.php">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li class="">
<a href="test.php">
<i class="material-icons">group</i>
<span>Test</span>
</a>
</li>
<li class="">
<a href="test2.php">
<i class="material-icons">people</i>
<span>Test2</span>
</a>
</li>
</ul>
</div>
And the script code:
$(document).ready(function () {
$('.menu .list a').click(function(e) {
$('.menu li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
The contents of test.php are as follows:
<body class="theme-red">
<nav class="navbar">
<?php include_once('navbar.html'); ?>
</nav>
<section>
<aside id="leftsidebar" class="sidebar">
<?php include_once('left-side-bar.html');?>
</aside>
</section>
<section class="content">
<div class="container-fluid">
<div class="row clearfix">
<table id="tbl-users" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</tfoot>
<tbody>
<?php
$accounts = get_details();
foreach($accounts as $acc){
?>
<tr>
<td><?php echo $acc['id']; ?></td>
<td><?php echo $acc['name']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</section>
</body>
Why is the problem arising?
The problem arises that, when you use e.preventDefault() on click of
anchor tag, the default behaviour is to redirect the page and that's
why the page doesn't load but the active class gets added. But when
you don't use e.preventDefault(), the page redirects immediately
and the change you did happen but before it was redirected and not
for the new page(which could be redirected current page or some other page), that's why you can't see the class active added to
it.
.
How to fix the problem?
Well, there are a couple of ways to go about it. I'd say that from the
test.php or test2.php return a value, which you can validate against
the javascript with if-else conditions, if the value matches you make
that li class as active.
Here's the changes you need to make:
Add a span on each of your pages to which you have hyperlinked i.e test.php, test2.php, etc. having text the same as your hyperlink in the anchor tag so for test.php add a span as:
<span id="curpage" style="display:none;">test.php</span>
Then, add a script at the end of your body tag (you may be able to add this script in a seperate file and include in all of your php files using <?php include(".."); ?> :
$('a[href=\"' + $("#curpage").text() + '\"]').parent().addClass("active");
Here's a sample code, that you can try and implement. Make 2 files in
the same directory named as a.html having the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<span id="curpage" style="display:none;">a.html</span>
<div class="menu">
<li>1</li>
<li>2</li>
</div>
<script>
$('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>
And b.html having the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<span id="curpage" style="display:none;">b.html</span>
<div class="menu">
<li>1</li>
<li>2</li>
</div>
<script>
$('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>
And now when you change the pages by clicking the link, you can see
how the color of bullet changes.
I don't think you should be changing the "active" class just when the li links are clicked. Think that when you redirect your users to a specific page from another, the li links "OnClick" event won't be fired at all, hence, the active menu link won't be displayed appropriately.
Now, what I usually do to solve this issue (don't know if it's the most elegant solution, but it works) is to place a tag at the top of each html content template (I'm assuming you're using templates for the Header, Footer and Content here), I give it a descriptive ID, like "page-name" or "section", and add a data attribute to it with the name of the menu link that this page "belongs" to:
<div id="page-name" data-page="home-page">
Then with JQuery you can ask for the div's data like this:
var current_page = $("#page-name").data("page");
And simply alter the menu links class depending on what page the user is currently in:
// remove the "active" class from ALL the links first
$(".menu li a").removeClass("active");
if (current_page === "home-page") {
// add the "active" class just to the link you want
$("#home-page-link").addClass("active")
}
Of course, you would do that with a switch and you would have to load the js file on ALL pages (that's why the use of the Header template is so important, since you would just need to include it once). Also, in the html "data-page" attribute, the "page" part can be anything, just remember to call it appropriately later.
Hope I helped.
To dynamically add a class, on page load, to the navigation item of the current page, consider:
Checking the current page url: $(location).attr('href') OR
$(location).attr('pathname')
Looping through anchor elements (a) of the navigation menu to
determine if any of the href attribute values match the current
page url with a conditional check using the .indexOf() method:
if(anchorEl.indexOf(currentPageUrl) >= 0)
If any do, add the required class, using the .addClass() method:
$(this).addClass('current');
Code Snippet Demonstration:
Note: Intended for the sake of demonstration
The code snippet embedded below uses specific urls to provide a working example and to demonstrate the intended functionality. Adjust accordingly to apply to a given production environment.
$(document).ready(function () {
var currentPageUrl = $(location).attr('href'), // store current page url in variable
anchorEl;
$('.menu a').each(function(){
anchorEl = $(this).attr('href'); // store href atribute of current anchor element in iteration
console.log('anchor link url:',anchorEl);
console.log('current url of window:',currentPageUrl);
if(anchorEl.indexOf(currentPageUrl) >= 0) { // if anchor element contains
$(this).addClass('current');
console.log('class "current" was added.');
}
});
});
/*
Note:
$(location).attr('href') = full absolute path (https://stacksnippets.net/js)
$(location).attr('pathname') = relative path (/js)
*/
.current {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<ul class="list">
<li>
<a href="https://stacksnippets.net/foobar1">
<span>foobar #1</span>
</a>
</li>
<li>
<a href="https://stacksnippets.net/foobar2">
<span>foobar #2</span>
</a>
</li>
<li>
<a href="https://stacksnippets.net/js">
<span>This should be the <em>current</em> url</span>
</a>
</li>
</ul>
</div>
You should know e.preventDefault() will prevent default behavior of that object which called on it (redirect in this case). So you are preventing your application from redirect to that href you specified.
You can change your function code like this:
$(document).ready(function () {
$('.menu .list a').click(function(e) {
$('.menu li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
//Here is needed change
location.href = $(this).attr('href');
});
});
Edit 1:
So you can work like this approach:
1) Specify a class name for each li tag
2) Send the class name that must has active class after redirection and page load
3) Read the passed class name from url and add/remove to/from your li tags
So your html code will be as following:
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="home active">
<a href="index.php">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li class="group">
<a href="test.php">
<i class="material-icons">group</i>
<span>Test</span>
</a>
</li>
<li class="people">
<a href="test2.php">
<i class="material-icons">people</i>
<span>Test2</span>
</a>
</li>
</ul>
</div>
If you need to script code according to this solution which I explained, so I will update my answer.
Edit 2:
You need to have below script codes in your file:
function setActiveClass() {
//Remove active class from all li tags
$('.menu li.active').removeClass('active');
//Find current url
var url = $(location).attr('href');
if (url.contains("activeClass")) {
//Find the index of active class in url
var start = url.indexOf("#activeClass");
//Add 6 unit to start index because of the longest class name is people which has 6 character
var end = start + 6;
//Fetch passed class name from url
var className = url.substring(start, end);
//Add active class corresponding to passed class name
if(className.contains("home"))
$(".home").addClass('active');
else if(className.contains("group"))
$(".group").addClass('active');
else
$(".people").addClass('active');
} else {
//Add active class for default mode (when we have not any redirect yet)
$("#defaultLiTag").addClass('active');
}
}
$(document).ready(function () {
//Call the function
setActiveClass();
$('.menu .list a').click(function(e) {
e.preventDefault();
var classNameOfParent = $(this).parent().attr('class');
var classNameToBePassedByUrl = "home";
if(classNameOfParent.contains("group"))
classNameToBePassedByUrl = "group";
else if(classNameOfParent.contains("people"))
classNameToBePassedByUrl = "people";
location.href = $(this).attr('href') + "#activeClass=" + classNameToBePassedByUrl;
});
});
i had the same problem after a lot of searching i could find this solution in this link i hope it could help you. Although you should remove class active and add class active to clicked navbar item ,you should use location.href to add active class when the new page reload.
https://santosh-shah.com/add-class-active-page-refresh-jquery/
I have the <ul> tag as below. When clicked on the anchor link it should display a div with the ul list items underneath. On the click function of anchor tag, I need to get the complete height of the div (in fact the height of the ul with li items), the submenu
<ul>
<li>
<a></a>
<div>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</li>
</ul>
The html code is as below:
<ul class="menu level-1 plain" id="header-menu">
#{
var i = 1; //Used for submenu ID
}
#foreach (var menuItem in Model.Header.TopLevelNavigation)
{
if (i < 6)
{
<li #Html.Raw(i > Model.MenuMidPoint ? "class=\"sub-menu-nudge-left\"" : "")>
#if (menuItem.ContentLink.HasChildPages())
{
<a href="#sub-menu-#i" class="menu-link js-ui-header-all-menu-drill-down" aria-haspopup="true">
<span class="icon icon-chevron-left #Model.GetBoxIcon(i)"></span>
<span>#menuItem.Name</span>
</a>
<div id="sub-menu-#i" class="sub-menu" aria-label="submenu" aria-hidden="true">
#Html.DisplayEnumerableIContent("<ul class=\"level-2 plain\">{0}</ul>", "<li>{0}</li>", "menu-link", menuItem.ContentLink.GetChildPages(true, true))
</div>
}
</li>
}
i++;
}
</ul>
I tried the jquery function as below:
I tried as below, but I am unable to get the height of the submenu. It never gets into the foreach loop at all. Could anyone please help
$(".menu-link").click(function () {
var $subnavdev = $(this).parent().sublings('sub-menu').siblings('level-2 plain')
var totalHeight = 0;
$subnavdev.find('li').each(function() {
totalHeight += $(this).outerHeight(true);
});
alert(totalHeight);
});
Some of your class selectors were not specified correctly, plus there was a typographical error (all on Line 2).
Update - It also seems the siblings() methods may not be behaving as you intend them to... - And I got the .level-2 selector wrong still - since you need another . before plain. (See below example)
By using the closest() method you can go up to the nearest parent (for example, <li>), then use find() to pick out all .level-2.plain items nested within that parent.
Remember that your $(this) inside the handler function refers to the handled element, (in this case the .menu-link item being clicked.
$(".menu-link").click(function () {
var $subnavdev = $(this).closest('li').find('.level-2.plain');
// ...
});
I would like to show the active tab's name (text) in a span .active-class.
Example:
<ul class="tabs">
<li class="feinleinen active">feinleinen</li>
<li class="glatt">glatt</li>
</ul >
<span class="active-class">*Active_Tab_Name_Here (i.e. feinleinen) *</span>
What you want is either to have a click event each time a link is clicked and put the text in there?
Javascript:
function changeSpan(var newText){
document.getElementByClassName('active-class').innterHTML(newText);
}
When the above you need to initialise the function. this can be done in the anchor within the list item.
<li><a href='#' onclick='changeSpan("new item name!");'>
Don't forget the hash (#) within the href! This stops the default action, in layman's terms.
With jQuery this can be a bit simpler
$('a','ul.tabs>li').click(function(){//a classname would be a better selector
$('.active-class').appendTo($(this).innerHTML());//can also use $(this).text();
return false;//also stops default action
});
FIDDLE:
HTML
<ul class="tabs">
<li class="feinleinen active">feinleinen
</li>
<li class="glatt">glatt
</li>
</ul>
<span class="active-class">active tab name here</span>
SCRIPT
$('.active-class').text($('.tabs .active').find('a').text());
I guess you want this on click , therefore bit updation to my above code here :-
$('.tabs a').click(function () {
$('.tabs li').removeClass('active');
$(this).parent('li').addClass('active');
$('.active-class').text($(this).text());
});
fiddle: http://jsfiddle.net/x97g8sc7/
$(".active-class").text($(".tabs .active").text());
I am very close but just can't see what I am missing in the jQuery script to only display the correct block of content based upon the anchor clicked and want to display initially to a visitor the first block of content from the anchors. Any help is appreciated.
I have dynamically generated anchor links with a class of .link
The content is also dynamically generated and each anchor point (A, B, C...) has it's content contained in a ul class of .test-full-list. Any help is appreciated.
Generated content:
Anchor links:
<span class="link">A</span>
<span class="link">B</span>
Content:
<div class="test-listing-container">
<ul class="test-full-list">
<ul class="test-category-list">
<a name="A"></a>
<div class="anchor-header">- A -</div>
<li id=test-list>
Some Link 1
Some Link 1
</li>
</ul>
</ul>
</div>
Script:
jQuery(document).ready(function () {
jQuery('.test-listing-container').hide();
jQuery('.link a').click(function () {
var jQuerydiv = jQuery('.test-full-list').eq(jQuery(this).index('.link a'));
jQuerydiv.show('.test-full-list'); // show the relevant div
});
});
If you're bringing in content dynamically, your .click() will not work. This is because the element you are trying to attach the click to hasn't been generated.
You can replace this:
jQuery('.link a').click(function() {
With this:
jQuery('.test-listing-container').on('click', '.link a', function() {
If that doesn't work:
jQuery(document).on('click', '.link a', function() {
Edit: Adding a fiddle to demo the code: http://jsfiddle.net/Fm6bR/1/
Assuming you can't change the markup slightly, you may do the following
A
B
<div class="test-listing-container">
<ul class="test-full-list">
<ul class="test-category-list">
<a name="A"></a>
<div class="anchor-header">- A -</div>
<li id=test-list>
Some Link 1
Some Link 1
</li>
</ul>
</ul>
</div>
jQuery(document).ready(function(){
jQuery('ul.test-category-list').hide();
jQuery('ul.test-category-list').first().show(); //show the first one by default
jQuery(document).on('click', '.link a', function (evt) {
var $a = jQuery(evt.currentTarget),
name = $a.attr('href').substr(1),
$a2 = jQuery('.test-listing-container').find('a[name="' + name + '"]'),
$ul = $a2.parents('ul.test-category-list').first();
jQuery('ul.test-category-list').hide(); // hide all
$ul.show(); // show the relevant one
});
});
Generate the content with an id based on the anchor name or some other unique identifer of the content. set data-content on each link to the id of the contents id. then use jquery to get the content by using .data function on the link in the click function
HTML
<span class="link">A</span>
<span class="link">B</span>
<div class="test-listing-container">
<ul class="test-full-list" id="fulllistA">
<ul class="test-category-list">
<li id=test-list>
Some Link 1
Some Link 1
</li>
</ul>
</ul>
</div>
Javascript
jQuery(document).on("click",".link a",function(e){
e.preventDefault();
e.stopPropagation();
var content = jQuery("#"+jQuery(this).data("content"));
jQuery(".test-listing-container > ul").not(content).hide(); // hide the others.
content.show();
});