disable li and don't allow to click - javascript

i use twitter bootstrap and jquery.
Depending of a variable, i would like to disable and remove the possibility to click
<ul class="nav nav-pills nav-stacked">
<li id="member" role="presentation" data-toggle="tab" class="active"><span class="glyphicon glyphicon-inbox"></span> Membres</li>
<li id="subscription" role="presentation" data-toggle="tab"><span class="glyphicon glyphicon-bed"></span> Abonnements</li>
</ul>
i tried this code
if (role != "ROLE_ADMIN") {
$('#subscription').addClass("disabled").find("a").attr("onclick", "return false;");
$('#report').addClass("disabled").find("a").attr("onclick", "return false;");
$('#user').addClass("disabled").find("a").attr("onclick", "return false;");
$('#setup').addClass("disabled").find("a").attr("onclick", "return false;");
} else {
$("#subscription").removeClass("disabled").find("a").removeAttr("onclick");
$("#report").removeClass("disabled").find("a").removeAttr("onclick");
$("#user").removeClass("disabled").find("a").removeAttr("onclick");
$("#setup").removeClass("disabled").find("a").removeAttr("onclick");
}
li is disabled, but i can click on it...
Edit
$('#user').prop('onclick',null).off('click');
seem to do the job

Add some styles to your disabled class like
.disabled{
pointer-events:none;
opacity:0.7;
}

just because it appears disabled does not necessarily mean it is disabled. you will have to listen to events and prevent their default action to disable them.
or, using CSS you can use pointer-events: none;

Your code can be simplified a lot. If you want to remove the 'clickable' styles of your links, try this:
js
if (role != "ROLE_ADMIN") {
$('#subscription, #report, #user, #setup')
.addClass("disabled")
.find("a").prop("disabled", true);
} else {
$('#subscription, #report, #user, #setup')
.removeClass("disabled")
.find("a").prop("disabled", false);
}
css
.disabled a {
pointer-events: none;
color: grey;
}
Here is a working fiddle

Add disabled class to your element and then add this JS script to prevent clicking on disabled elements :
$('a').click(function () {
if ($(this).hasClass('disabled')) {
return false;
}
});

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>

javascript color toggles between two links working, not resetting when they need to

I have two links popularity and new. if I click "popularity" it should turn green until I click "new". and vice versa for "new". And this works great. But thing is when I click home button that's in my navbar, the green color on the link should be gone. they should go back to the color they were before they are clicked.
my code
<div id="Space">
<ul id="shouldwork">
<li role="presentation" class="sort">
<a class="norang" href="/?sort=score&page=1" style="text-decoration:none;">popularity</a>
</li>
<li role="presentation" class="date">
<a class="updated" href="/?sort=date&page=1" style="text-decoration:none;">new</a>
</li>
</ul>
</div>
<script>
//on page load
var ul_li_a = $("ul#shouldwork>li>a");
var lastClickTag = localStorage.getItem("last_clicked");
ul_li_a.css("color", "black");
if(lastClickTag){
$("."+lastClickTag).css("color", "green")
}
$('ul#shouldwork>li').on("click", function(){
ul_li_a.css("color", "black");
$(this).children("a").css("color", "green");
localStorage.setItem("last_clicked", $(this).children("a").attr("class"));
});
</script>
and in navbar I have
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'index' %}">home</a>
</div>
I would do this with an .active class in CSS in order to make it more modular and easy to understand. Then, I would change the color based on your query strings, rather than using local storage.
I didn't have a way to test this so let me know if it works. If not, let me know what error is displaying in the console. I'm sure I may have missed something in the JS.
Here is a codepen if you'd rather look at it there: http://codepen.io/anon/pen/xVGYWE?editors=1111
HTML (links are removed as they broke in codepen, added class .link for better targeting in jQuery)
<div id="Space">
<ul class="shouldwork">
<li role="presentation" class="sort">
<a class="link norang" href="#">popularity</a>
</li>
<li role="presentation" class="date">
<a class="link updated" href="#">new</a>
</li>
</ul>
</div>
CSS
.link {
color: blue;
text-decoration: none;
}
.link:hover {
color: navy;
text-decoration: none;
}
.link.active {
color: green;
}
jQuery
// change on click
var link = $('.link');
link.on("click", function(){
// remove any active classes
link.removeClass("active");
// add active class to link that was clicked
$(this).addClass("active");
});
// set up get query strings from URL
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// see if the page is indeed sorted
var sort = getParameterByName('sort')
// if it has a query string of sort=score, make that active
if ( sort == "score") {
$(".sort a").addClass("active");
}
// if it has a query string of sort=date, make that active
if ( sort == "date") {
$(".date a").addClass("active");
}
Why should they go back to the original color? You never told them to.
$('.navbar-brand').on('click',function(){
ul_li_a.css("color", "black");
})
You could utilize both .addClass and .removeClass, and create another CSS class that changes the color back when you click the home button. This would be more seamless if you took the css out of your js code, and just use these two methods to switch between the classes you need on the home button click event.
edit: or what he said ^. There are many options.
Based on your problem description, and a quick scan of your code, it looks like you are properly setting the color when the two items themselves are clicked, but you have no function to handle unsetting the color when something else is clicked ... i.e. in your function that fires on-click, just check that if neither is used, clear the green color.
Alternatively, you could use something like is used here ... i.e. a conditional something along the lines of this: if(a[i].href.split("#")[0] == window.location.href.split("#")[0]). Then, just apply the green color if either of your two links are active.
Hope this helps!
If you can use ids for links, change your code as below. Check demo - Fiddle.
var ul_li_a = $("ul#shouldwork>li>a");
var lastClickTag = localStorage.getItem("last_clicked");
if(lastClickTag){
$("#"+lastClickTag).addClass('green');
}
ul_li_a.on("click", function(){
ul_li_a.removeClass('green');
$(this).addClass('green');
localStorage.setItem("last_clicked", this.id);
});
$('.navbar-brand').click( function() {
ul_li_a.removeClass('green');
$("#"+lastClickTag).addClass('green');
})
HTML:
<ul id="shouldwork">
<li role="presentation" class="sort">
<a id="norang" href=".." style="text-decoration:none;">popularity</a>
</li>
<li role="presentation" class="date">
<a id="updated" href=".." style="text-decoration:none;">new</a>
</li>
</ul>
CSS:
.green {
color: green;
}
Clearing your lastClickTag from the local storage must resolve your issue along with this code.
$('.navbar-brand').on('click',function(){
localStorage.removeItem("last_clicked");
})
remove this local storage. So your if(lastClickTag){ function will not be executed, And your color will remain black.

Toggle submenu and if child clicked go to page

I've built a simple toggle menu that when clicked once shows a list of child elements and if clicked again hides those visible elements.
If a child element is clicked however I want it to visit that page only I cant seem to get it working? Is it to do with my prevent Default?
// Language select in global nav
$('.sub-lang').on('click', function(e) {
if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
$(this).removeClass('active');
$(this).css('height', 'auto');
$(this).children('ul').hide();
} else {
$(this).addClass('active');
$(this).css('height', $(this).find('ul').height() + 65);
$(this).children('ul').show();
}
e.preventDefault();
});
Here is the JsFiddle
Why don't you simple transform your main menu element in paragraph tag ?
or you could put an # inside your main menu element, and delete prevent default.
In this way you don't need to prevent default on your main elements.
Although google.com doesn't load inside an iFrame, you could check this fiddle. It works.
Look at this (with # in the anchors) fiddle
HTML
<ul style=" ">
<li class="sub-lang">
English
<ul style="">
<li>International</li>
<li>UK & Ireland</li>
</ul>
</li>
<li class="sub-lang">
Espanol
<ul style="">
<li>Español</li>
<li>España</li>
</ul>
</li>
<li class="sub-lang">
Francais
<ul style="">
<li>Français</li>
<li>France</li>
</ul>
</li>
</ul>
Add this line before your code
$('.sub-lang > a').removeAttr('href');
Remove
e.preventDefault();
this should work fine
You should add one condition for that.
if($(e.target).parent().hasClass('sub-lang') )
It will allow you to click on submenu.
// Language select in global nav
$('.sub-lang').on('click', function(e) {
if($(e.target).parent().hasClass('sub-lang') ){
if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
$(this).removeClass('active');
$(this).css('height', 'auto');
$(this).children('ul').hide();
} else {
$(this).addClass('active');
$(this).css('height', $(this).find('ul').height() + 65);
$(this).children('ul').show();
}
e.preventDefault();
}
});
ul li ul {
display: none;
z-index: 2;
right: 0;
background-color: #fff;
width: 250px;
}
ul li.active ul {
display: block;
text-align:left;
background: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style=" ">
<li class="sub-lang">
English
<ul style="">
<li>International</li>
<li>UK & Ireland</li>
</ul>
</li>
<li class="sub-lang">
Español
<ul style="">
<li>España</li>
</ul>
</li>
<li class="sub-lang">
Français
<ul style="">
<li>France</li>
</ul>
</li>
</ul>
Working Fiddle
Hope it helps.
Here Check This Out.
Explaination.
Instead of delegating the event on the whole li, I bound the event to all the immediate <a> children of the li, and then prevent the propagation for that specific element. So we don't have to figure out how to stop the event propagation (click in our case) to the children element.
Also the JSFiddle may have loading external iframe problems, so check the solution out here.
I think you have to add stopPropagation in your inside list items.
$('.sub-lang ul li').on('click', function(e) {
e.stopPropagation();
});

Jquery click function not working (displaying a hidden section)

I am trying to create a popup section that contains a form for someone to enter their email address when someone clicks on a link that says 'Mailing List.' The trouble is that when I click the link, the section doesn't appear. It works when I set it to hover but not click. I've run out of ideas on how to debug this. What am I missing?
HTML
<form class="mailing-list-input pull-right">
<input type="text" placeholder="Email Address" class="mailing-list-input">
<button class="mailing-list-btn">
<img src="/assets/arrow.png" style="height: 12px; width: 12px; margin-right: 6px;">
</button>
</form>
<footer class="footer footer-style">
<section class="container pull-right">
<ul class="list-inline btm-list">
<li class="btm-menu-width">
<a href="/" class="btm-menu-heading mailing-list">
Mailing List
</a>
</li>
</ul>
</section>
</footer>
CSS for .mailing-list-input
.mailing-list-input {
margin-right: 10rem;
display: none;
z-index: 98;
position: fixed;
bottom: 5rem;
right: 0;
}
Jquery File
$(document).ready(function() {
$(".mailing-list").click(function() {
$(".mailing-list-input").css('display', 'block');
},
function() {
$(".mailing-list-input").css('display', 'none')
})
})
The click function only accepts a single handler function. To achieve the behaviour you want, use a single handler and toggle() the element. Try this:
$(".mailing-list").click(function(e) {
e.preventDefault();
$(".mailing-list-input").toggle();
});
Example fiddle
Note I also added preventDefault() to stop the default link behaviour.
Based on what the OP appears to be trying to do this should be the Javascript:
$(".mailing-list").click(function(e) {
e.preventDefault();
if ($(".mailing-list-input").css('display') === 'block') {
$(".mailing-list-input").css('display', 'none');
} else {
$(".mailing-list-input").css('display', 'block');
}
});
The click handler callback takes an argument that is the event object, you can call preventDefault on that object to stop the event from continuing through its lifecycle. Then if you want the link to toggle the element on every click you check to see if the element is visible or not and set its value accordingly.
Here is a working fiddle

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