I have any AJAX call that allow to select an item, I'm displaying the selected item with a darker background and the icon marked selected.
I can change the background but when I attempt to change the icon doesn't work. Somebody can explain what I'm doing wrong?
Here it is the code
$("#accounts-list").on('click', '.nav-link', function () {
var object_id = $(this).data('object-id');
$.ajax({
url: "url_to_ajax_call.php",
data: {
'account_id': object_id
},
type: 'POST',
success: function (response) {
// remove class where previously selected
$(".nav-link").removeClass("bg-soft-primary"); // background
$(".nav-link>span.fa-check-circle").removeClass("fa-check-circle").addClass("fa-circle"); // remove checked icon
// apply selected class to the new item
let item = $('.nav-link[data-object-id=' + object_id + ']');
item.addClass('bg-soft-primary'); // apply background
$(item + ">span.fa-circle").removeClass("fa-circle").addClass("fa-circle"); // select checked icon
}
})
})
<div id="accounts-list">
<ul class="nav">
<li class="nav-item">
<div class="nav-link nav-link-card-details bg-soft-primary"
data-object-id="1">
<span class="far fa-check-circle"></span>
Item 1
</div>
</li>
<li class="nav-item">
<div class="nav-link nav-link-card-details"
data-object-id="2">
<span class="far fa-circle"></span>
Item 2
</div>
</li>
<li class="nav-item">
<div class="nav-link nav-link-card-details"
data-object-id="3">
<span class="far fa-circle"></span>
Item 3
</div>
</li><li class="nav-item">
<div class="nav-link nav-link-card-details"
data-object-id="4">
<span class="far fa-circle"></span>
Item 4
</div>
</li>
</li>
</ul>
</div>
Thank you
In $(item + ">span.fa-circle"), item is not a string to be used has a selector... It is a jQuery object.
So do it like this:
item.find("span.far")
Ho! To notice any effect, the should be two fontAwesome classes (one added and one different removed ;)
.removeClass("fa-check-circle").addClass("fa-circle")
Another way would be:
.toggleClass("fa-check-circle fa-circle")
Related
Hi and thanks in advance for your help!
I have previously used JS to add an active class to an element if the corresponding URL shows.
I am trying to take what I have done in the past and edit it.
I am trying to add an active class to an element if the href attribute equals '#tab1' for example. Rather than if the URL matches.
Please see the existing JS below that I am trying to work from, I have tried a few things including a getelementbyID rather than selecting the href but I'm lost.
$(document).ready(function () {
const $links = $('.hs-mega-menu ul li a');
$.each($links, function (index, link) {
if (link.href == (document.URL)) {
$(this).addClass('active');
}
});
});
An example of one of the nav-links I am trying to select and apply the active class too are below:
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
There are a few ways to do this, you can use a function like you have or you can filter or just use a selector for the attribute. Here are examples of the latter two.
$(function() {
let testurl = "#tab1";
const $links = $('.hs-mega-menu ul li a');
$links.filter(function(index, link) {
return $(this).attr('href') == testurl;
}).addClass("active");
$links.filter("[href='" + testurl + "']").addClass("active-test")
});
.active {
color: green;
}
.active-test {
background-color: #ffddff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hs-mega-menu">
<ul>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab2" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
</ul>
</div>
- List item
<ul class="nav nav-tabs-outline">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#shot-Title">Title</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#shot-Description" id="disco">Description</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#shot-Details">Details</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#shot-Skills">Exprtise and Skills</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#shot-Budget">Budget</a>
</li>
</ul>
JavaScript
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('#jobpostname').keyup(function () {
if ($(this).val() == '') {
//Check to see if there is any text entered
// If there is no text within the input then disable the button
$('#disco').prop('disabled', true);
} else {
//If there is text in the input, then enable the button
$('#disco').prop('disabled', false);
}
});
});
</script>
There is a input element in title tag , what i want to do is when i type something in title input the description link should get activated ,
is there a way to active the 'nav-link disabled' using jquery?
Hi Aksingh welcome to Stackoverflow's community.
In your code disabled and active are classes not attributes or properties.
So you can use jQuery's addClass and removeClass methods to solve your problem
try this code..
$(document).ready(function(){
$('#jobpostname').keyup(function () {
if ($(this).val() == '') {
//Check to see if there is any text entered
// If there is no text within the input then disable the button
$('#disco').addClass('disabled');
$('#disco').removeClass('active');
} else {
//If there is text in the input, then enable the button
$('#disco').addClass('active');
$('#disco').removeClass('disabled');
}
});
});
I looked for similar posts but they all seem to resort to Jquery, which by now is considered outdated in most cases.
My question is:
How can I change the class of active (currently on my "Projects" labeled tag, to the siblings when clicking it?
I'm really trying to achieve results with only Vanilla Javascript and hopefully a .forEach method, to make it more functional.
Sorry for not providing any JS at this moment, it seems I'm really struggling with the basics .
<nav id="sidebar">
<div class="toggle-btn" onclick="toggleSidebar()">
<i class="fas fa-angle-double-right fa-2x"></i>
</div>
<ul class="navbar-nav">
<li class="nav-item">
PROJECTS
</li>
<li class="nav-item">
CREATION PROCESS
</li>
<li class="nav-item">
BEFORE AND AFTER
</li>
<li class="nav-item">
ABOUT THE STUDIO
</li>
<li class="nav-item">
CONTACT
</li>
</ul>
</nav>
EDIT:
Thanks to the first reply, I managed to figure out a clean and modern way to refactor it to my taste:
const tabs = document.querySelectorAll('.nav-link');
tabs.forEach(tab => tab.addEventListener('click', toggleActiveTab));
function toggleActiveTab(e) {
tabs.forEach(tab => {
tab.classList.remove('active');
});
e.currentTarget.classList.toggle('active');
}
Here you go with a solution
var items = document.getElementsByClassName('nav-link');
for (var i = 0; i < items.length; i++) {
items[i].addEventListener('click', printDetails);
}
function printDetails(e) {
for (var i = 0; i < items.length; i++) {
if (items[i].classList.contains("active")) {
items[i].classList.toggle("active")
}
}
this.classList.add("active");
}
.active {
background: #ddd;
}
<nav id="sidebar">
<div class="toggle-btn" onclick="toggleSidebar()">
<i class="fas fa-angle-double-right fa-2x"></i>
</div>
<ul class="navbar-nav">
<li class="nav-item">
PROJECTS
</li>
<li class="nav-item">
CREATION PROCESS
</li>
<li class="nav-item">
BEFORE AND AFTER
</li>
<li class="nav-item">
ABOUT THE STUDIO
</li>
<li class="nav-item">
CONTACT
</li>
</ul>
</nav>
Add an event listener to each nav-link if you can't add onClick event to HTML code.
Then in the click method check for active class in each nav-link element, if active class is present then toggle it.
Then add active class to the clicked tab.
In my index.html i have a JQuery var which i need to set when the user clicks an option from the left hand menu and its needed to show/hide fields depending on the selection made as the page is shared between 3 pages but displays different fields depending on the option.
But i have an issue when sometimes when the option is selected, its not setting the var as expected then after a few other clicks, it then decides to play ball and set it, then when ever it wants, it will stop again.
There no errors what so ever so not sure how to track or stop it.
JQuery
$('li').on('click', function (event) {
selectedLinkId = event.target.id.toLowerCase();
// Admin menu option clicked
if ($(this).is($("li[name*='admin']"))) {
selectedLink = 'adminMenuOption';
}
// Reseller menu option clicked
else if ($(this).is($("li[name*='reseller']"))) {
selectedLink = 'resellerMenuOption';
}
// Channel menu option clicked
else if ($(this).is($("li[name*='channel']"))) {
selectedLink = 'channelMenuOption';
}
// Customer menu option clicked
else if ($(this).is($("li[name*='customer']"))) {
selectedLink = 'customerMenuOption';
}
// Any other menu option clickedf
else {
selectedLink = 'generalMenuOption';
}
$('#mainSearchSection').show();
})
Part of HTML
<ul class="nav nav-tabs nav-pills flex-column" role="tablist">
<li class="nav-item" id="adminSearchLink" name="adminOptions">
<div class="nav-link d-flex align-items-center option pl-6">
Search for
<i id="adminSearchMenuIcon" class="material-icons ml-auto mr-0">arrow_drop_up</i>
</div>
</li>
<li class="nav-item" name="adminSearchOptions">
<a id="adminSearchCustomerLink" class="nav-link d-flex align-items-center option" href="#" data-toggle="tab" role="tab" aria-selected="false">
<span class="ml-5 pl-4">Customer</span>
</a>
</li>
<li class="nav-item" name="adminSearchOptions">
<a id="adminSearchNumberLink" class="nav-link d-flex align-items-center option" href="#" data-toggle="tab" role="tab" aria-selected="false">
<span class="ml-5 pl-4">Number</span>
</a>
</li>
<li class="nav-item" name="adminSearchOptions">
<a id="adminSearchResellerLink" class="nav-link d-flex align-items-center option" href="#" data-toggle="tab" role="tab" aria-selected="false">
<span class="ml-5 pl-4">Reseller</span>
</a>
</li>
</ul>
Console.Log Output
Other Page JQuery Which Reads The Var
var selectedLinkId;
if (selectedLinkId.includes('reseller')) {
$('#accStatusCol, #companyNameCol, #nameFieldCol').show();
$('#nameField').focus();
} else if (selectedLinkId.includes('channel')) {
$('#accStatusCol, #companyNameCol, #nameFieldCol').hide();
} else if (selectedLinkId.includes('customer')) {
$('#accStatusCol, #companyNameCol').show();
$('#companyNameField').focus();
}
You seems to want to get the id of the clicked <a> element. However the event is bound to the <li> element.
When you use event.target it will give you the element that you clicked. Because events are bubbling it is not always the same element but can be any of the children of the element that the event handler is bound to. So sometimes you get the <li> element, sometimes the <a> element and sometimes the <span> element. If you want to get the id of the first a element all the times you can do $(this).children('a').first().attr('id').
The problem is that you're sometimes clicking on the <span> and sometimes on the <a>, outside the text. Only the latter has an id.
Use $('li a').click(...) and
selectedLinkId = $(this).attr('id').toLowerCase();
This way, this always refers to the <a>, and getting the id from that never fails.
The non-jQuery variant is to use event.currentTarget.id.toLowerCase(), which always refers to the element that the listener was attached to as it bubbles up the tree.
I have a Sidebar / Menu that I am working with. It has been created with Bootstrap, DJango, and Javascript.
Basically, I am trying to write Javascript so that when on clicks on a menu-item, the background changes color (dark blue), the icon change color (light green / turquoise) and it gets a type of "wedge"
Below is an example of a menu-item that has been chosen (Dashboard) along with menu-items that have not been chosen (Security and Messages). The "wedge" has a red arrow pointing to it.
Here is the HTML code that is being used:
[... snip ...]
<div class="page-container">
<div class="page-sidebar-wrapper">
<div class="page-sidebar navbar-collapse collapse">
<ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu "
data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="nav-item start active open">
<a href="{% url 'mainadmin:dashboard' %}" class="nav-link nav-toggle">
<i class="fa fa-tachometer"></i>
<span class="title">Dashboard</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:security' %}" class="nav-link nav-toggle">
<i class="fa fa-users"></i>
<span class="title">Security</span>
<span class="arrow"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link nav-toggle">
<i class="fa fa-comment"></i>
<span class="title">Messages</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List All Messages</span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List My Messages</span>
<span class="badge badge-danger"></span>
</a>
</li>
</ul>
</li>
[... snip ...]
Here is the Javascript code:
<script>
$(document).ready(function () {
$('.nav-item a').click(function(e) {
$('.nav-item a').removeClass('selected');
$('.nav-item a').removeClass('arrow');
$('.nav-item a').removeClass('open');
$('.nav-item a').removeClass('active');
alert("I have gotten in");
var $parent = $(this).parent();
$parent.addClass('selected');
$parent.addClass('arrow');
$parent.addClass('open');
$parent.addClass('active');
e.preventDefault();
});
});
</script>
I do get the alert message - but - what happens is :
-> the background of the chosen menu-item does change color - which is correct
--> The icon of the chosen menu-item changes color (to light blue / turquoise) - which is correct
-> the tick of the arrow does not take place for the chosen menu-item :(
-> the old chosen menu item does not "de-select"
What am I doing wrong?
TIA
Hi #Joe Lissner
Thanks so much for the response!
I had to add the following to get the "wedge" portion to work. It required span tags
// REFERENCE: https://stackoverflow.com/questions/2013710/add-span-tag-within-anchor-in-jquery
$(this).append('<span class="selected"></span>');
$(this).append('<span class="arrow open"></span>');
While this works when clicking on the main-menu item, I'm not so lucky when it comes to clicking on sub-menu items. As of now, I am pretty much new to Javascript.
How would one get the sub-menu items to work?
Also, when clicking on an item, it does not go to the page specified in "href="
How would can one make changes to the code so that when the menu-item is clicked, it would go to the page specified in "href="
Again, thanks for the response :-)
You are removing the classes from the a tags, not the .nav-item elements.
Try this:
$(document).ready(function () {
$('.nav-item a').click(function(e) {
e.preventDefault(); // best practice to have this first, if you remove this line then the link will function as expected.
var $parent = $(this).parent();
var $arrow = $parent.find('.arrow');
$('.nav-item').removeClass('selected arrow open active'); // simplified
$('.nav-item .arrow').removeClass('open');
$('.nav-item .selected').detach(); // remove the span that was there before
alert("I have gotten in");
$parent.addClass('open active'); // simplified
$arrow.addClass('open').before('<span class="selected" />')
});
});
Edit - Fixed the issue with the arrow