addClass and removeCLass in JS with loading content - javascript

I have problem with addClass and removeCLass in JS. I would like to do sth like that:
But I have a content div where I load files in PHP. But when I load sth the script resets and first li is selected. Scheme:
I click on Events, it gets new class and the content is load. Now when I click events, page loads and I see the content but class in first li.
How to change it?
EDIT:
OK guys I change code but it still doesn't work as I want. When I chenge "#" in links to url, the page loads as new and I lost this JS. (It starts again).
CODE:
$(document).ready(function () {
$("#MB1").click(function () {
$(this).addClass("active");
$("#MB2").removeClass("active");
$("#MB3").removeClass("active");
$("#MB4").removeClass("active");
});
});
$(document).ready(function () {
$("#MB2").click(function () {
$(this).addClass("active");
$("#MB1").removeClass("active");
$("#MB3").removeClass("active");
$("#MB4").removeClass("active");
});
});
$(document).ready(function () {
$("#MB3").click(function () {
$(this).addClass("active");
$("#MB1").removeClass("active");
$("#MB2").removeClass("active");
$("#MB4").removeClass("active");
});
});
$(document).ready(function () {
$("#MB4").click(function () {
$(this).addClass("active");
$("#MB1").removeClass("active");
$("#MB2").removeClass("active");
$("#MB3").removeClass("active");
});
});
#menu-div ul{
list-style-type:none;
}
.button a{
text-decoration: none;
color:green;
}
.button a:hover{
color: red;
}
.button.active a{
text-decoration: underline;
}
<div id="menu-div">
<ul>
<li id="MB1" class="button active">Home</li>
<li id="MB2" class="button">Projects</li>
<li id="MB3" class="button">About Us</li>
<li id="MB4" class="button">Contact</li>
</ul>
</div>

What happens when you assign the click action using
$('#menu li a').on('click', function(){
$('li a.current').removeClass('current');
$(this).addClass('current');
});
is that only the existing objects receive the event-handler.
You want to use something like this instead:
$("body").on('click', '#menu li a', function(){
$('li a.current').removeClass('current');
$(this).addClass('current');
});
By making body the target, even if the data loads after the script, the event-handler will be set.
In addition, any subsequent changes to the menu won't require you to reset the event handler.
EDIT
Per the changes to your example code:
When you have <a href="#" and so on, pressing the link does not make you leave the page.
You changed some of the links to <a href="?something" and so on. Clicking this link, the whole page is reloaded with the new querystring.
Are the links supposed to get data asynchronously?
If YES, you should return the jquery to the way it was... and use my answer above instead of the one you used of $(document).ready({[...].
If NO, I would suggest that you use PHP to make sure that the correct menu item is set to active.
Something along the lines of (I don't actually know php... this code may be completely off):
<a href="?whatever" class="button <?php if(request.querystring = "whatever") echo "active"; ?>
<a href="?something" class="button <?php if(request.querystring = "something") echo "active"; ?>

Related

toggle active on nav-tabs

$('.active').click(function() {
$(this).toggleClass('active');
$(this).toggleClass('active');
});
I know this is totally wrong but I'm new and trying to learn; What I'm trying to do is toggle the active class for the <li> onclick() really appreciate any help. Thankyou.
<ul class="nav nav-tabs">
<li role="presentation" onclick="toggleClass();">Hi</li>
</ul>
You need to create a function toggleClass
JS
Create a new function toggleClass which will accept the current clicked element
function toggleClass(elem) {
$(elem).toggleClass('active');
};
HTML
add toggleClass function to onclick handler & pass the current element as an argument
<li role="presentation" onclick="toggleClass(this);">Hi</li>
CSS
Create a class .active
.active {
background: yellow;
}
DEMO
What you need to do is set all other elements's classes to inactive,
$('.active').className = 'inactive';
$(this).className = 'active';
That top expression will affect all elements with the class and the bottom one will change the current clicked element.
try this:
$("nav li").click(function() {
$(this).toggleClass("active");
});
if only for <li> elements with active class
$("nav li.active").click(function() {
$(this).toggleClass("active");
});
This is not how Bootstrap is supposed to work. If you are using bootstrap, use their tab js component. more on it here
Basically you add a listener on those LI tags like this: (from the docs)
$('.nav.nav-tabs li').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
The way you did, you were toggling the state twice so in the end it would stay the same.
I think instead of $('.active').click(function()), you should target li click as
$( "li" ).click(function() {
$(this).toggleClass("active");
});
fiddle:
http://jsfiddle.net/wVVbT/142/
Here is a link for description about how to use .toggleClass.
toggleClass: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
DEMO:
$('li').click(function() {
$(this).toggleClass('active');
})
ul li{
float: left;
margin-right: 20px;
}
.active {
background: #69a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> Link A</li>
<li>Link B</li>
</ul>

How to addClass and remove Class when clicking a link?

I'm trying to make some elements active when I click on a link. I'm at this code right now which let's me add and remove active class when I click on element with class 'test'. What I need is to click a link and have the same behaviour to the div elements.
I have:
$('.test').on('click',function(){
$('.test.active').removeClass('active');
$(this).addClass('active');
});
.active{
color: #F00;
}
<div class='test active'>test</div>
<div class='test'>test</div>
<a class='link' href=''>Click me</a>
This code adds and removes the active class when I click the divs. How to do the same thing by clicking the link?
When you click a link, the behavior and the method will be the same as if you click a button, a div, or any other element of the page.
The difference is that an <a> element will redirect you to another page (inclusive if it's "the same" where you come from) and the changes won't be noticeable.
You will need to use $("element").addClass("class");
Add href="javascript:;" if to avoid redirection.
In jQuery below snippet will work:
$('.link').on('click', function(){
$(this).toggleClass('active');
})
Working Fiddle
Update
To highlight multiple divs
$('.link').on('click', function(){
if($('.test.active').next().hasClass('test'))
{
$('.test.active').removeClass('active').next('.test').addClass('active');
}
else
{
$('.test.active').removeClass('active');
$('.test:first').addClass('active');
}
})
Updated Fiddle
Your code should be:
$('.link').on('click', function () {
var $nextActive = $('.test.active').next('.test').length ? $('.test.active').next('.test') : $('.test').first();
$('.test.active').add($nextActive).toggleClass('active');
return false;
});
You can do like following. It will add and remove active class on link click.
$('.link').on('click', function(){
$('.active').removeClass('active').siblings('.test').addClass('active');
});
.active{
color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='test active'>test</div>
<div class='test'>test</div>
<a class='link' href='#'>Click me</a>
Edit:
This will work for infinite div.
JQuery:
$('.link').on('click', function(){
if($('.active').next().hasClass('test'))
{
$('.active').removeClass('active').next('.test').addClass('active');
}
else
{
$('.active').removeClass('active');
$('.test:first').addClass('active');
}
});
Fiddle
Just remove .active class.
below code is working.
$('.test').click(function(){
$('.test').removeClass('active');
$(this).addClass('active');
});
replace js function
$('.test').on('click',function(){
$('.test').removeClass('active');
$(this).addClass('active');
});
Demo Link https://jsfiddle.net/ffjcfb2b/
According to your post and comments you'd like to use link as class changer for divs. Here you go. Edited!
$('.link').on('click', function(){
$('.test.active').toggleClass('active').next().addClass("active");
});
Working fiddle

Changing the website-url to http://my.url#menuitem on click on menu item?

I'm writing a small website where I already implemented a JavaScript code to change to content of a div if an item in the menu bar is clicked. I know have the problem, that if someone refreshes the website, they are at the start-page again. I want to change this so the name of the menu item is added to the url with a # in front of it. Wikipedia does this in some way if you click on an item in the content-overview of an article.
My question is now how I can achieve this?
This is my current JavaScript code:
$(function() {
$('#menu ul li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
$('#content').load(page);
});
});
And this the menu part of my HTML:
<div id="menu">
<ul>
<li>Über mich</li>
<li>Kinesiologie</li>
<li>Körbler Symbole</li>
<li>Energiearbeit</li>
<li>Ernährungsberatung</li>
<li>Diätberatung</li>
<li>Food Coach</li>
<li>Heilkräuterberater</li>
<li>Heilkräuterprodukte</li>
<ul>
<li>Salben</li>
<li>Öle</li>
<li>Pflege</li>
<li>Bad/Dusche</li>
<li>Allerlei</li>
</ul>
</ul>
</div>
And sorry for the bad description, I have absolutely no idea how to call this.
You can try this:-
At first add an attribute in the menu.
<div id="menu">
<ul>
<li data-btn-name="ueber_mich">Über mich</li>
<li data-btn-name="kinesiologie">Kinesiologie</li>
</ul>
</div>
At the time of clicking on the menu change the location hash of the page
$(function() {
$('#menu ul li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
window.location.hash = $(this).attr('data-btn-name');
$('#content').load(page);
});
});
At the time of opening the page first time, load the content depending on the hash.
$('document').ready(function(){
if(window.location.hash){
$('#content').load('./content/'+window.location.hash+'.html');
}
})
you can simply use this if text name is same as file name:
$(function() {
$('#menu ul li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
window.location.hash = $(this).text();// if you want to show text of the li
console.log($(this).text());
$('#content').load(page);
});
});

jquery make action when link menu item is clicked

I have three menu items here:
JSFIDDLE: FIDDLE LINK
<div class="home-content">
<div class="menu-bar">
<ul class="nav nav-tabs">
<li class="active">Blue<sup>beta</sup></li>
<li>Green<sup>beta</sup></li>
<li>Red</li>
</ul>
</div>
By default link blue is active.
I want whenever any link green or red is clicked, it should be active
Color of the label should be changed as per the link selected
I am facing trouble in this points.
You could add a DATA color on your li like that :
<li data-color="#0f0">Green<sup>beta</sup></li>
then use this code :
$(function () {
$(".menu-bar li a").click(function () {
$('.active').removeClass('active'); //Remove the current active item
var color = $(this).closest('li').addClass('active').data('color'); //add class the the target and save his data attribute
$("#l1").css("color", color); //Change color
});
});
Fiddle : http://jsfiddle.net/ZjgV4/6/
Something like this?
$(function () {
$(".menu-bar li a").click(function () {
$(".menu-bar li").removeClass("active");
$(this).parent().addClass("active");
});
});
http://jsfiddle.net/3mhCW/1/
Without completely doing everything, this should point you on the right track. A few things to note about your code - You should pass in the e event, to the click handler and use jQuery's e.preventDefault(); to stop the link. Also, you need to quote the value in the css function. .css("color", "red") otherwise you will get an undefined error that red is not defined. Instead of manipulating the css of the elements, I would use add/removeClass respectively and style the elements with css.
$(function () {
$(".menu-bar li a").click(function (e) {
e.preventDefault(); // stop the link from following the href
// remove the active class from everything
$(".active").removeClass("active");
// $(this).css("color", "red");
$(this).addClass("active");
});
});
I included the code here.
basically, i inserted the color name to a class each color has its own class and each LI has a global attribute data-* with the value of the color (the name of the class)
HTML:
add to all the li the attribute data-color="blue"
Add CSS:
.blue{
background-color:blue;
}
.green{
background-color:green;
}
.red{
background-color:red;
}
jQuery:
$(function () {
$(".menu-bar li a").click(function () {
$('.menu-bar li.active').removeClass('active');
$(this).parent().addClass('active');
$("#l1").attr('class',$('.menu-bar li.active').attr('data-color'));
});
});

Can you disable tabs in Bootstrap?

Can you disable tabs in Bootstrap 2.0 like you can disable buttons?
You could remove the data-toggle="tab" attribute from the tab as it's hooked up using live/delegate events
As of 2.1, from bootstrap documentation at http://twitter.github.com/bootstrap/components.html#navs, you can.
Disabled state
For any nav component (tabs, pills, or list), add .disabled for gray
links and no hover effects. Links will remain clickable, however,
unless you remove the href attribute. Alternatively, you could
implement custom JavaScript to prevent those clicks.
See https://github.com/twitter/bootstrap/issues/2764 for the feature add discussion.
I added the following Javascript to prevent clicks on disabled links:
$(".nav-tabs a[data-toggle=tab]").on("click", function(e) {
if ($(this).hasClass("disabled")) {
e.preventDefault();
return false;
}
});
i think the best solution is disabling with css.
You define a new class and you turn off the mouse events on it:
.disabledTab{
pointer-events: none;
}
And then you assign this class to the desired li element:
<li class="disabled disabledTab"> .... </li>
You can add/remove the class with jQuery also. For example, to disable all tabs:
$("ul.nav li").removeClass('active').addClass('disabledTab');
Here is an example: jsFiddle
No Need Any Jquery, Just One Line CSS
.nav-tabs li.disabled a {
pointer-events: none;
}
Also, I'm using following solution:
$('a[data-toggle="tab"]').on('click', function(){
if ($(this).parent('li').hasClass('disabled')) {
return false;
};
});
Now you just adding class 'disabled' to the parent li and tab doesn't work and become gray.
Old question but it kind of pointed me in the right direction. The method I went for was to add the disabled class to the li and then added the following code to my Javascript file.
$('.nav-tabs li.disabled > a[data-toggle=tab]').on('click', function(e) {
e.stopImmediatePropagation();
});
This will disable any link where the li has a class of disabled. Kind of similar to totas's answer but it won't run the if every time a user clicks any tab link and it doesn't use return false.
Hopefully it'll be useful to someone!
For my use, the best solution was a mix of some of the answers here, which are :
Adding the disabled class to the li I want to disable
Add this piece of JS :
$(".nav .disabled>a").on("click", function(e) {
e.preventDefault();
return false;
});
You can even remove the data-toggle="tab" attribute if you want Bootstrap to not interfer at all with your code.
NOTE: The JS code here is important, even if you remove the data-toggle because otherwise, it will update your URL by adding the #your-id value to it, which is not recommended because your tab is disabled, thus should not be accessed.
With only css, you can define two css classes.
<style type="text/css">
/* Over the pointer-events:none, set the cursor to not-allowed.
On this way you will have a more user friendly cursor. */
.disabledTab {
cursor: not-allowed;
}
/* Clicks are not permitted and change the opacity. */
li.disabledTab > a[data-toggle="tab"] {
pointer-events: none;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
</style>
This is an html template. The only thing needed is to set the class to your preferred list item.
<ul class="nav nav-tabs tab-header">
<li>
Info
</li>
<li class="disabledTab">
Date
</li>
<li>
Photo
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab-info">Info</div>
<div class="tab-pane active" id="tab-date">Date</div>
<div class="tab-pane active" id="tab-photo">Photo</div>
</div>
Suppose, this is your TAB and you want to disable it
<li class="" id="groups"><a data-toggle="tab" class="navuserli" href="#groups" aria-expanded="false">Groups</a></li>
So you can also disable this tab by adding dynamic css
$('#groups').css('pointer-events', 'none')
In addition to James's answer:
If you need to disable the link use
$('a[data-toggle="tab"]').addClass('disabled');
If you need to prevent a disabled link from loading the tab
$('a[data-toggle="tab"]').click(function(e){
if($this.hasClass("disabled")){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
}
If you need to unable the link
$('a[data-toggle="tab"]').removeClass('disabled');
You can disable a tab in bootstrap 4 by adding class disabled to the child of nav-item as follows
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#messages7" role="tab" aria-expanded="false">
<i class="icofont icofont-ui-message"></i>Home</a>
<div class="slide"></div>
</li>
I tried all suggested answers, but finally i made it work like this
if (false) //your condition
{
$("a[data-toggle='tab'").prop('disabled', true);
$("a[data-toggle='tab'").each(function () {
$(this).prop('data-href', $(this).attr('href')); // hold you original href
$(this).attr('href', '#'); // clear href
});
$("a[data-toggle='tab'").addClass('disabled-link');
}
else
{
$("a[data-toggle='tab'").prop('disabled', false);
$("a[data-toggle='tab'").each(function () {
$(this).attr('href', $(this).prop('data-href')); // restore original href
});
$("a[data-toggle='tab'").removeClass('disabled-link');
}
// if you want to show extra messages that the tab is disabled for a reason
$("a[data-toggle='tab'").click(function(){
alert('Tab is disabled for a reason');
});
None of the answers work for me. Remove data-toggle="tab" from the a prevents the tab from activating, but it also adds the #tabId hash to the URL. That is unacceptable to me. What is also unacceptable is using javascript.
What does work is added the disabled class to the li and removing the href attribute of its containing a.
my tabs were in panels, so i added a class='disabled' to the tabs anchor
in javascript i added:
$(selector + ' a[data-toggle="tab"]').on('show.bs.tab', function (e) {
if ($(this).hasClass('disabled')){
e.preventDefault();
return false;
}
})
and for presentation in less i added:
.panel-heading{
display:table;
width:100%;
padding-bottom:10px;
ul.nav-tabs{
display:table-cell;
vertical-align:bottom;
a.disabled{
.text-muted;
cursor:default;
&:hover{
background-color:transparent;
border:none;
}
}
}
}
Most easy and clean solution to avoid this is adding onclick="return false;" to a tag.
<ul class="nav nav-tabs">
<li class="active">
Home
</li>
<li>
Approval Details
</li>
</ul>
Adding "cursor:no-drop;" just makes cursor look disabled, but is clickable, Url gets appending with href target for ex page.apsx#Home
No need of adding "disabled" class to <li> AND removing href
Here's my attempt. To disable a tab:
Add "disabled" class to tab's LI;
Remove 'data-toggle' attribute from LI > A;
Suppress 'click' event on LI > A.
Code:
var toggleTabs = function(state) {
disabledTabs = ['#tab2', '#tab3'];
$.each(disabledTabs, $.proxy(function(idx, tabSelector) {
tab = $(tabSelector);
if (tab.length) {
if (state) {
// Enable tab click.
$(tab).toggleClass('disabled', false);
$('a', tab).attr('data-toggle', 'tab').off('click');
} else {
// Disable tab click.
$(tab).toggleClass('disabled', true);
$('a', tab).removeAttr('data-toggle').on('click', function(e){
e.preventDefault();
});
}
}
}, this));
};
toggleTabs.call(myTabContainer, true);

Categories

Resources