Toggle and untoggle three buttons - javascript

I have three buttons and I want to toggle between them. How can I add and remove the toggle and untoggle classes to have to toggle appropriately.
Right now, both buttons can be selected/toggled on. There should only be one button toggled at a time but I also want to be able to deselect/untoggle all of the buttons. So that I have
an option of not toggling the buttons on.
Here's the buttons in my view:
<div id="drawing">
<div style="margin-top: 12px; padding-left: 8px; margin-bottom: 8px">
<button class="small-button" onclick="Drawing.AngleClick()" data-val-btnname="Angle" style="width: 70px; height: 20px;"><span>#Culture.GetString("Angle")</span></button>
</div>
<div style="margin-top: 12px; padding-left: 8px;">
<button class="small-button" onclick="Drawing.PointClick()" data-val-btnname="Point" style="width: 70px; height: 20px;"><span style="font-size:10px !important">#Culture.GetString("Point")</span></button>
<button class="small-button" data-val-btnname="ClearAll" style="width: 70px;" onclick="Drawing.Delete()"><span>#Culture.GetString("ClearAll")</span></button>
</div>
</div>
Here's the js function so far for one of the buttons (I have the same if statement in my other button):
AngleClick: function () {
var button = $('body').find("button[data-val-btnname='Angle']");
if (button.hasClass('small-toggled-button')) {
button.removeClass('small-toggled-button').addClass('small-button');
} else {
button.removeClass('small-button').addClass('small-toggled-button');
}
}

This is an easy method for toggling buttons. Run the snippet to see it work. I simplified your HTML only for the sake of shortening the example--I'm not suggesting you change it.
$(document).ready(function() {
$("#drawing button").click(function(e) {
var isActive = $(this).hasClass('active');
$('.active').removeClass('active');
if (!isActive) {
$(this).addClass('active');
}
});
});
.active {
background: #555555;
color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="drawing">
<button class="small-button">Angle</button>
<button class="small-button">Point</button>
<button class="small-button">ClearAll</button>
</div>

Related

jQuery multiple button show and hide elements when click

I have a multiple buttons has show and hide class. Which is also activate the elements every toggle click. I want to make it a shorter code and make it globally. Please help me how to do it. All I want is to achieve a lesser code and same with the result.. Thank you.
$('.show').on('click', function () {
$(this).addClass('inactive');
$('.hide').removeClass('inactive');
$('.helloworld').removeClass('inactive')
})
$('.hide').on('click', function () {
$(this).addClass('inactive');
$('.show').removeClass('inactive');
$('.helloworld').addClass('inactive')
})
$('.ok').on('click', function () {
$(this).addClass('inactive');
$('.cancel').removeClass('inactive');
$('.thanks').removeClass('inactive')
})
$('.cancel').on('click', function () {
$(this).addClass('inactive');
$('.ok').removeClass('inactive');
$('.thanks').addClass('inactive')
})
<style>
.inactive{
display:none;
}
button{
padding:5px 25px;
color: #fff;
background-color:#1d9bf0;
margin-top: 10px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="show"> + Show </button>
<button class="hide inactive"> - Hide </button>
<p class="helloworld inactive">Hello WOrld</p>
<br>
<button class="ok"> + Ok </button>
<button class="cancel inactive"> - Cancel </button>
<p class="thanks inactive">Thank you</p>
The technique you're looking for here is DRY, or Don't Repeat Yourself. To do this, look for the common patterns in the logic you have.
In this case each button has its text updated, and it changes the state of it's following sibling. Therefore you can place common class attributes on the elements so that the same JS logic can be applied to them all. From there you can use jQuery's DOM traversal methods to relate the elements to each other, and also data attributes to store custom metadata about the elements which can be used when the click event occurs.
Finally you can use toggleClass() to add/remove the classes to display/hide the elements as necessary.
Here's a working example:
$('.toggle').on('click', e => {
let $btn = $(e.target);
$btn
.text(() => $btn.data($btn.hasClass('show') ? 'hide-text' : 'show-text')).toggleClass('show') // update text
.next().toggleClass('inactive'); // toggle related content
})
<style>
.inactive {
display: none;
}
button {
padding: 5px 25px;
color: #fff;
background-color: #1d9bf0;
margin-top: 10px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-container">
<button class="toggle show" data-show-text="+ Show" data-hide-text="- Hide">+ Show</button>
<p class="content inactive">Hello WOrld</p>
</div>
<div class="toggle-container">
<button class="toggle show" data-show-text="+ Ok" data-hide-text="- Cancel">+ Ok</button>
<p class="content inactive">Thank you</p>
</div>

Check to see of current clicked element equals to previous clicked element-Javascript

I have a list of items displayed in a container with a dropdown associated with every container.A snippet of how the container list looks:
http://jsfiddle.net/jHpKB/2/
When I click on the button , the dropdown menu shows up, however, when I try to click on any other button button, the dd stays and does not hide. the list is dynamically created. What I was trying to do is if the current clicked element is same as that of the previous clicked elemnt, then hide the first dd menu
Is there way to check if a clicked element is equal to the previous clicked element in javascript(no jquery)
code:
afterRender: function() {
this.el.on('click', function(e) {
//here i want to check (if e.getTarget() === secondClickedEment) { //do something}
},this);
}
is this possible?
Thanks
You can test object equality with jQuery using the is function. Requires 1.6 or higher.
var stuff = $('#stuff');
var thing = stuff;
if (stuff.is(thing)) {
// the same
}
So for your situation this should work:
afterRender: function() {
this.el.on('click', function(e) {
var clickedElm = $(e.getTarget());
var secondElm = $(secondClickedElm);
if (clickedElm.is(secondElm)){
// same elements
}
},this);
}
jQuery example:
use var lastClicked; to hold the last clicked element, then each click check if the same one clicked then reset the lastclicked, otherwise update the lastclicked.
var lastClicked;
$('.container').on('click', function(e) {
if (this == lastClicked) {
lastClicked = '';
$(this).children('.menu').hide();
} else {
lastClicked = this;
$('.menu').hide();
$(this).children('.menu').show();
}
});
.container {
border: 1px solid #333;
height: 300px;
width: 200px;
float: right;
margin-right: 20px;
}
.menu {
display: none;
}
.button {
border: 1px solid #333;
background: #333;
float: right;
height: 20px;
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
One way to do this would be to dynamically add/remove a class to the div, indicating if it's open or not. Then on click, you could just toggle that class.
Example:
let containers = document.getElementsByClassName('container');
for (let i=0; i<containers.length; i++) {
let button = containers.item(i).getElementsByClassName('button')[0];
let menu = containers.item(i).getElementsByClassName('menu' )[0];
button.addEventListener('click', function() {
menu.classList.toggle('open');
});
}
Then in your CSS:
.open {
display: block;
}

Javascript - show a button inside of a DIV when clicked (and hide all others)

I have a list of DIVS that have buttons inside. By default, all buttons are hidden. When I click within a DIV area, the current button inside of this clicked DIV are should show (class='.db') AND all previously clicked/shown buttons should be hidden (class='.dn'). In other words, at any time there should be only one button (currently clicked) shown and all other should be hidden.
I want to use vanilla Javascript and tried this below, but it won't work. I feel there is some small error but don't know where.. Note - the DIVS and buttons don't have their own unique IDs (they only have the same CSS (.posted) classes.
PS - maybe it'd be better not to add this onClick="t();" to each DIV and use an 'addEventListener' function, but this is way too much for me ; )
CSS:
.dn {display:none}
.db {display:block}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
HTML:
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
JAVASCRIPT:
function t()
{
var x=document.getElementsByClassName("posted"),i,y=document.getElementsByTagName("button");
for(i=0;i<x.length;i++)
{
x[i].y[0].className="dn";
};
x.y[0].className='db';//make sure the currently clicked DIV shows this button (?)
}
You might want to read more about selector, how to select class, block level etc.
some link might be helpful:
CSS selector:
https://www.w3schools.com/cssref/css_selectors.asp
jQuery selector:
https://api.jquery.com/category/selectors/
Solution - Using jQuery:
$('.posted').on('click', function() {
//find all class called posted with child called dn, then hide them all
$('.posted .dn').hide();
//find this clicked div, find a child called dn and show it
$(this).find('.dn').show();
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
Solution - Pure js version:
//get list of div block with class="posted"
var divlist = Array.prototype.slice.call(document.getElementsByClassName('posted'));
//for each div
divlist.forEach(function(item) {
//add click event for this div
item.addEventListener("click", function() {
//hide all button first
divlist.forEach(function(el) {
el.getElementsByTagName('button')[0].classList.add('dn');
});
//show button of the div clicked
this.getElementsByTagName('button')[0].classList.remove('dn');
}, false);
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
You can do this with with plain JavaScript using Event Bubbling, querySelector and the element classList attribute like this.
Change your HTML to look like this:
<div class="posts">
<div class="posted">
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
</div>
Then use JavaScript like this:
var posts = document.querySelector('.posts');
var allPosted = document.querySelectorAll('.posted');
//clicks bubble up into the posts DIV
posts.addEventListener('click', function(evt){
var divClickedIn = evt.target;
//hide all the buttons
allPosted.forEach(function(posted){
var postedBtn = posted.querySelector('button');
postedBtn.classList.remove('db');
});
// show the button in the clicked DIV
divClickedIn.querySelector('button').classList.add('db')
});
You can find a working example here: http://output.jsbin.com/saroyit
Here is very simple example using jQuery .siblings method:
$(function () {
$('.posted').click(function () {
$('button', this).show();
$(this).siblings().find('button').hide();
});
});
https://jsfiddle.net/3tg6o1q7/

Multiple show/hide buttons with button text change on click

i have a wordpress page with several buttons, that show/hide a certain div, also the button text changes from "more info" to "less info" according to button click.
This is my code so far, but as i have multiple buttons, of course each time i click on one, the code is executed for all hidden divs and button texts.
What has the code to be like, that it only affects the one button actually clicked / hidden div at a time?
Heres the HTML:
<a class="clicker reveal" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
and JS:
<script type="text/javascript">
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery(".slider").hide();
jQuery('.reveal').click(function() {
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
} else {
jQuery(this).text('MORE INFOS');
}
});
jQuery(".clicker").click(function(){
jQuery(".slider").slideToggle("slow");
jQuery.each(masterslider_instances, function(i, slider) {
slider.api.update();
slider.api.__resize(true);
jQuery.each(slider.controls, function( index, control ) {
if (control.realignThumbs) control.realignThumbs();
});
jQuery.each(masterslider_instances, function(a,b){
b.api.update(true);
});
});
});
});
</script>
and the targeted div:
<div class="slider>Some content</div>
Thank you in advance!
UPDATE
I am informed that the button is in a div, the update reflects that small change:
From:
var tgt = $(this).next('.slider');
To:
var tgt = $(this).parent().next('.slider');
The following demo uses the class methods. Details are provided within the source in the comments.
SNIPPET
/*
Removed a chunk of meaningless code
since there's no way of using it
because the plugin isn't
provided (I'm assuming).
*/
$(function() {
/*
Combined both the `more/less` and
`slideToggle()` features under one
class(`.reveal`) and one click event.
*/
$('.reveal').on('click', function(e) {
/*
Prevent anchor from default behavior
of jumping to a location.
*/
e.preventDefault();
/*
See if `.reveal` has class `.more`
*/
var more = $(this).hasClass('more');
/*
`.tgt` is the next `.slider` after
`this`(clicked `a.reveal`).
*/
var tgt = $(this).parent().next('.slider');
/*
Toggle `.reveal`'s state between `.more` and
`.less` classes. (See CSS)
*/
if (more) {
$(this).removeClass('more').addClass('less');
} else {
$(this).removeClass('less').addClass('more');
}
/*
`slideToggle()` only the `div.slider` that
follows `this` (clicked `a.reveal`)
*/
tgt.slideToggle('slow');
});
});
.reveal {
display: block;
}
.reveal.more:before {
content: 'MORE INFO';
}
.reveal.less:before {
content: 'LESS INFO';
}
.slider {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
Try this
jQuery('.reveal').each(function(idx,item) {
jQuery(item).click(function(){
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
}
else {
jQuery(this).text('MORE INFOS');
}
});
});
Here is working Fiddle
Make a reference between the anchor and div by using data attribute.
<a class="clicker reveal" data-target="slider-1" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
<div class="slider slider-1">Some content</div>
Now, you can do the following-
jQuery('.clicker').click(function() {
var targetDiv = jQuery('.' + jQuery(this).attr('data-target'))
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
targetDiv.slideDown('slow');
} else {
jQuery(this).text('MORE INFOS');
targetDiv.slideUp('slow');
}
// do the rest of your stuff here
});

Remove specific event handler from child of element

In my application I want to resize a window when user clicks on panel-heading, but that heading contains a child element- button which has another event handler binded on. What I need to do is, when user click on that button, no resize function will be called. I tried many variations, but none of them worked.
HTML:
<div class="panel-heading" style="cursor:pointer">
<div class="pull-right">
<button type="button" class="btn btn-danger btn-xs" id="btn-subject-remove"><span class="glyphicon glyphicon-remove"></span> Remove</button>
</div>
</div>
And my jq is:
$('#btn-subject-remove').on('click',btnRemoveSubjectsClick);
$('#subscribers-row .panel-heading').on('click',btnResizeClick);
What I have tried, but none of them worked:
$('#subscribers-row .panel-heading').off('click','#btn-subject-remove',btnResizeClick);
$('#btn-subject-remove').off('click',btnResizeClick);
$('#subscribers-row .panel-heading').on('click',btnResizeClick).children().click(function(e){return false});
I also tried checking in btnResizeClick function what element was clicked, and if it was remove button then return false, but the clicked element is still panel-heading
Any suggestions?
Bind a click event on the children and use e.stopPropagation() to block the parent click event.
In a simple example:
$(function() {
$('div').on('click', function() {
$(this).toggleClass('redBg');
});
$('div>*').on('click', function(e) {
e.stopPropagation();
});
});
div {
background: green;
width: 200px;
height: 200px;
}
span {
display: block;
height: 50px;
background: yellow;
}
.redBg {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
With some text
<span> in a span </span>
</div>

Categories

Resources