jQuery toggle through Twitter Bootstrap button classes - javascript

Scenario
I would like the user to be able to toggle through the Twitter Bootstrap button classes using jQuery when the main part of the button is clicked (for quickness).
Or
Allow the user to select a state from the drop down menu.
Whatever the state selected, the whole btn-group should have the same button class.
Not Started (btn-info), In Progress (btn-warning), Completed (btn-success) and Late (btn-error).
What I would like
What I have so far
This is my HTML code. It is standard Bootstrap button group.
<div class="btn-group">
<button type="button" class="btn btn-warning">Week 7</button>
<button type="button" class="btn btn-warning dropdown-toggle"
data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
Not Started
</li>
<li>
In Progress
</li>
<li>
Completed
</li>
<li class="divider"></li>
<li>
Late
</li>
</ul>
</div>
This toggles all of the buttons, not just the button that is clicked.
$('.btn-group').click(function () {
var classes = ['btn btn-info','btn btn-info','btn btn-success'];
$('.btn').each(function(){
this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
});
});

Without changing your HTML you could use the following JavaScript code:
//// TOGGLE ////
// toggle only if the first part of the button (button:first-child) is clicked
$('button:first-child').click(function () {
var classes = ['btn btn-info','btn btn-warning','btn btn-success','btn btn-danger'],
// select new class name first so it isn't changed on every iteration (if you use each)
oldClass = this.className,
newClass = classes[($.inArray(oldClass, classes)+1)%classes.length];
// this method keeps all other classes untouched (e.g. dropdown-toogle)
$([this, this.nextElementSibling])
.removeClass(oldClass)
.addClass(newClass);
});
//// SELECT ////
// add a click listener to every a element
$(".btn-group").each(function () {
var classes = ['btn-info','btn-warning','btn-success','btn-danger'],
buttons = $(this).children("button");
$(this).find("a").each(function (index) {
$(this).click(function () {
// use the a elements index to get the right array element
var newClass = classes[index];
$(buttons)
.removeClass(classes.join(' '))
.addClass(newClass);
});
});
});
Also see the live demo here: http://jsfiddle.net/b9e3ossu/1/
I hope that helps :).

Related

How to get a link that do nothing

I have created a search engine using Angular and Bootstrap. I have created different results tab as shown in image Tabs . Right clicking on tab does not show the option of a link as we get on any link.
link on right click
Currently I am using <li> tag and bootstrap to create the tabs of different result section. Here is the code for that
<ul type="none" id="search-options">
<li [class.active_view]="Display('all')" (click)="docClick()">All</li>
<li [class.active_view]="Display('images')" (click)="imageClick()">Images</li>
<li [class.active_view]="Display('videos')" (click)="videoClick()">Videos</li>
<li [class.active_view]="Display('news')" (click)="newsClick()">News</li>
<li class="dropdown">
<a href="#" id="settings" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Settings
</a>
<ul class="dropdown-menu" aria-labelledby="settings" id="setting-dropdown">
<li routerLink="/preferences">Search settings</li>
<li data-toggle="modal" data-target="#customization">Customization</li>
</ul>
</li>
<li class="dropdown">
<a href="#" id="tools" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Tools
</a>
<ul class="dropdown-menu" aria-labelledby="tools" id="tool-dropdown">
<li (click)="filterByContext()">Context Ranking</li>
<li (click)="filterByDate()">Sort by Date</li>
<li data-toggle="modal" data-target="#myModal">Advanced Search</li>
</ul>
</li>
</ul>
After clicking on the link everything is handled by the functions which get executed on click event. All I want to do that is make that a link, so that user can open it in new tab and state of the app should not change at all. How that is possible? I have tried to do that using routing but things became more complicated. i also followed some answers from here Make a HTML link that does nothing (literally nothing) but they do not work. Please help. I have tried all the answers from there opening link in new tab just disturbs the state of URL.
Using will make the page scroll to the top.
Use javascript:void(0):
Clicking here does nothing
Or equivalently, use javascript:;:
Clicking here does nothing
Or, with HTML5, just omit the href attribute:
<a>Clicking here does nothing</a>
You can use event.preventDefault() to prevent the default action of the link from being taken.
Valid Link<br>
<button id='hitMe'>Disable link</button>
<br/>
<button id="enable">Enable link</button>
<script>
document.getElementById('hitMe').onclick = function() { // button click
document.querySelectorAll('a').forEach(a =>{
a.onclick = function(e){
e.preventDefault();
return false;
}
});
};
document.getElementById("enable").onclick = function(){
document.querySelectorAll('a').forEach(a =>{
a.onclick = null;
});
}
</script>
By clicking the button, no more links will be followed.
Like this you still have the hover destination preview. Like google.de etc...
document.getElementById('hitMe').onclick = function() { // button click
[...document.querySelectorAll('a')].forEach(function(el){
el.onclick = function( e ) { // all 'a'
return false;
}
});
};
Valid Link<br>
<button id='hitMe'>Disable link.</button>
use
javascript:;
as href attribute
and add
event.preventDefault()
onclick method.
Click me

Clicking outside of an element to hide it, doesn't work with multiple elements

I want to hide multiple navigation bars when clicked outside of it, it makes sense to do so, But only one of them hides for one obvious reason.
HTML:
<nav class="navigation">
<ul>
<li><b>Aken</b></li>
<li class="right dropdown">
<a href="#" class="navigation-link nav-trigger">
Akar Muhamad
<img class="profile-picture" src="http://placehold.it/30x30/3498db/333">
<i class="fa fa-caret-down" aria-hidden="true" style="position: relative; right: 3%;"></i>
</a>
<div class="dropdown-content">
Profile
Settings
Logout
</div>
</li>
<li class="right dropdown">
<a href="#" class="navigation-link nav-trigger">
Akar Muhamad
<img class="profile-picture" src="http://placehold.it/30x30/3498db/333">
<i class="fa fa-caret-down" aria-hidden="true" style="position: relative; right: 3%;"></i>
</a>
<div class="dropdown-content">
Profile
Settings
Logout
</div>
</li>
</ul>
</nav>
JS:
$('.nav-trigger').on('click', function() {
// Loop through all the drop-downs, and make all of them invisible
// Except the one we clicked on.
$(this).siblings('.dropdown-content').toggleClass('visible');
var that = this;
$('.dropdown').each(function() {
if (that != this) {
$(this).siblings('.dropdown-content').removeClass('visible');
}
});
});
// TODO: Fix a bug where it doesn't work on multiple navigation bars.
$(document).on('click', function(event) {
if(event.target !== $('.nav-trigger')[0]) {
$('.dropdown').each(function() {
$(this).find('.dropdown-content').removeClass('visible');
});
}
});
Now, as you can see, I passed 0 as an index to check. But what I want is to loop through all of them and use the index as the key to that. Whenever I do that, it doesn't work at all, It also disables the click to show the navigation content function too.
Here's the JSBin.
You actually don't have to use loops here and you don't need to know the index.
$('.nav-trigger').on('click', function() {
// remove visible class from each .dropdown-content:
$('.dropdown-content').removeClass('visible');
// add visible class to .dropdown-content next to the clicked .nav-trigger:
$(this).siblings('.dropdown-content').addClass('visible');
});
$(document).on('click', function(event) {
// check if the clicked element is .nav-trigger:
$(event.target).is('.nav-trigger') ||
// if not, remove visible class from each .dropdown-content:
$('.dropdown-content').removeClass('visible');
});
JSFiddle Demo
Remove the loops and simply hide all of the dropdowns. Then add back the one you care about if necessary.
This code stores the dropdown visibility at click and uses it to toggle the visibility after hiding the dropdown content. This means that clicking the header will both open and close the dropdown.
$('.nav-trigger').on('click', function(event) {
// store current dropdown state
var visible = $(this).siblings('.dropdown-content').hasClass('visible');
// hide all dropdowns
$('.dropdown .dropdown-content').removeClass('visible');
// if we were visible, hide, and vice-versa
$(this).siblings('.dropdown-content').toggleClass('visible', !visible);
// prevent document handler from being fired
event.stopPropagation();
});
// hide all dropdowns if click propagates to document
$(document).on('click', function(event) {
$('.dropdown .dropdown-content').removeClass('visible');
});
JSBin

Get selected text from bootstrap dropdown

I have a bootstrap dropdown, and I want to keep the text of what is selected. I have tried most of the ways tried here, Get Value From html drop down menu in jquery , but there was never really an answer given, so I am still stuck.
<div id="tableDiv" class="dropdown">
<button id="tableButton" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Table
<span class="caret"></span>
</button>
<ul id="tableMenu" class="dropdown-menu">
<li>Att1</li>
<li>Att2</li>
<li>Att3</li>
</ul>
</div>
I have a js function that looks as follows
$("#tableMenu").click(function(){
var selText = $("#tableMenu").text();
document.getElementById("tableButton").innerHTML=selText;
});
but as explained in the above link, $("#tableMenu").text(); returns everything in the dropdown as a string, not just the one wanted. How do I get the text just from the one selected.
You need to attach the click() handler to the a element within the ul that gets toggled. You can then retrieve the text() of that element and set it to the related button. Try this:
$("#tableMenu a").on('click', function(e) {
e.preventDefault(); // cancel the link behaviour
var selText = $(this).text();
$("#tableButton").text(selText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableDiv" class="dropdown">
<button id="tableButton" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Table
<span class="caret"></span>
</button>
<ul id="tableMenu" class="dropdown-menu">
<li>Att1</li>
<li>Att2</li>
<li>Att3</li>
</ul>
</div>
Have you tried using an actual HTML drop down box and not an unordered list?
<select name="tableMenu" id="tableMenu" class="dropdown-menu">
<option value="Att1">Att1</option>
<option value="Att2">Att2</option>
<option value="Att3">Att3</option>
</select>
You should then be able to use:
var selText= document.getElementById("tableMenu").value;
Bind the click event to li and using this get the selected text and assign to the tab button text
$("#tableMenu li").click(function () {
var selText = $(this).text();
document.getElementById("tableButton").innerHTML = selText; // $("#tableButton").text(selText); //Using Jquery
});
Here's a vanillaJS way:
Given the following bootstrap 4 dropdown snippet:
<div class="dropdown-menu" id="select-color-dropdown" aria-labelledby="select-color">
<a class="dropdown-item" href="#">Red</a>
<a class="dropdown-item" href="#">Orange</a>
<a class="dropdown-item" href="#">Green</a>
<a class="dropdown-item" href="#">Gray</a>
</div>
One could write an event listener:
/* find web elements */
const colorSelectors = document.querySelector("#select-color-dropdown");
/* define event listeners */
const loadEventListeners = () => {
colorSelectors.addEventListener("click", (e) => {
e.preventDefault();
console.log(e.target.innerText);
});
}
/* Load all event listeners */
loadEventListeners();
which would print the selected option on every select (Red, Green...)

HTML JQuery: Pass selected value onclick to elements name

I currently have a dropdown menu so the user can select an option to refine their search by like so:
<button name = "toggle" tabindex="-3" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" >
<li><span class="t">restaurant</span></li>
<li> <span class="t">beauty salon</span></li>
<li> <span class="t">bars</span></li>
<li class="divider"></li>
<li> <span class="t">other</span></li>
</ul>
What I am wanting to do is when an option is selected from the drop down menu to update an elements name so I can then access whatever was selected on the form afters its been submitted. At the minute ive got this:
$(document).ready(function(){
$('ul.dropdown-menu li').click(function()
{
var field = document.createElement("input");
field.name=$(this).find("span.t").text();
}
});
});
How would I go about doing what i specified because I am a little unsure
If I have understood the question correctly you want to create an input element and update it's name property on the click event. If this is the case you can code:
$(document).ready(function() {
// create an input and append to #somewhere
var $field = $('<input>').appendTo('#somewhere');
$('ul.dropdown-menu li').click(function() {
$field.prop('name', $(this).find("span.t").text());
});
});
If the element should be generated on the first click:
var $field;
$('ul.dropdown-menu li').click(function() {
var name = $(this).find("span.t").text().trim();
if ( !$field ) {
$field = $('<input>', {
'type': 'text'
}).appendTo('#somewhere');
}
$field.prop('name', name);
});

Catching a click event on an <a> hyperlink with Backbone's Events function

I have recently switched from using two buttons to using a dropdown list of links in my backbone model.
Previously, this code captured these button clicks:
events: {
"click #expense-delete-button": "deleteRow",
"click #expense-copy-button": "copyRow",
},
This worked fine, but now that I've changed my html to this:
<div class ="expense-action-icons btn-group">
<button class="btn btn-mini dropdown-toggle" data-toggle="dropdown">
<i class="icon-cog"></i>
</button>
<ul class="dropdown-menu pull-right">
<li>
<a href="#" id="expense-copy-button">
<img src="../Images/copy.png"/>
Copy Entry
</a>
</li>
<li>
<a href="#" id="expense-delete-button">
<i class="icon-trash"></i>
Delete Entry
</a>
</li>
</ul>
</div>
The clicks are not being captured. I tried onclick as well and this didn't work.
You have to create the function inside your view.
events: {
"click #expense-delete-button": "deleteRow",
"click #expense-copy-button": "copyRow",
},
deleteRow:function(e){
e.preventDefault();
//Element clicked on
var target = $(e.currentTarget);
console.log('whatever you want');
},
copyRow:function(e){
//Element clicked on
var target = $(e.currentTarget);
console.log('copy your row');
},
initialize:function(){
//view code....
}

Categories

Resources