Buttons to behave as an Radio buttons - javascript

I have many different buttons that fires different functions. In this example, I created total of 3 buttons, each firing a different function. The reason I want to stay away from using a radio buttons itself is because at some point in time, two buttons must be active.
For this example, what I want to do is, when a button is active: for example, Apple button is active and it fires a function, Banana and pear button should be not active and not fire its functions and vice versa (Also, active button should be shaded in a different color)
How can I accomplish this? Here is my code so far:
$(document).ready(function() {
$('#AppleBTN').click(function() {
apple();
if ($(this).hasClass('active')) {}
$(this).toggleClass('active');
});
$('#BananaBTN').click(function() {
banana();
if ($(this).hasClass('active')) {}
$(this).toggleClass('active');
});
$('#PearBTN').click(function() {
pear();
if ($(this).hasClass('active')) {}
$(this).toggleClass('active');
});
});
function apple() {
alert('apple');
}
function banana() {
alert('banana');
}
function pear() {
alert('pear');
}
.btn {
background: #3498db;
border-radius: 0px;
font-family: Arial;
color: #ffffff;
font-size: 12px;
padding: 2px 2px 2px 2px;
text-decoration: none;
height: 30px;
width: 70px;
}
.btn.active,
.btn:active {
background: #124364;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="AppleBTN">Apple</button>
<button type="button" class="btn" id="BananaBTN">Banana</button>
<button type="button" class="btn" id="PearBTN">Pear</button>
I feel that, for each different button function, I need to create a class of 'inactive'. Also, I've been trying to look up to see if there is a .toggleClass('inactive') or .inactive but failed to find the right answer.

jsFiddle
Description
Basically this will iterate over all buttons in the div with class of btns it will then remove the class active from all buttons. From here it will add the active css class to the button clicked.
HTML
<div class="btns">
<button type="button" class="btn" id="AppleBTN">Apple</button>
<button type="button" class="btn" id="BananaBTN">Banana</button>
<button type="button" class="btn" id="PearBTN">Pear</button>
</div>
JS
$(document).ready(function() {
$('.btn').click(function() {
$('.btns > button').removeClass('active');
$(this).addClass('active');
// if you need to call a function you can pull any attribute of the button input
});
});

Make use of your .btn selector to target all three buttons, e.g. $('.btn'). Which is more maintainable than having to declare click event for each id.
$(document).ready(function() {
$('.btn').click(function() {
// remove active class except for the selected button
$('.btn').not(this).removeClass('active');
$(this).toggleClass('active');
// get the id of the button element
var id = $(this).attr("id");
if (id == "AppleBTN")
appleFunction();
else if (id == "BananaBTN")
bananaFunction();
else if (id == "PearBTN")
pearFunction();
});
});
Your different functions :
function appleFunction() {
alert("apple!");
}
function bananaFunction() {
alert("banana!");
}
function pearFunction() {
alert("pear!");
}
Fiddle

You can accomplish this with few lines of code. Attach a click event handler using .on(). Inside the event, remove the class active from any button it may currently be on using .removeClass(). Then add the active class to the current selection using .addClass().
$(function () {
$('.btn').on('click', function () {
$('.btn').removeClass('active');
$(this).addClass('active');
});
});
.btn {
background: #3498db;
border-radius: 0;
font-family: Arial;
color: #fff;
font-size: 12px;
padding: 2px;
text-decoration: none;
height: 30px;
width: 70px;
}
.btn.active, .btn:active {
background: #124364;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="AppleBTN">Apple</button>
<button type="button" class="btn" id="BananaBTN">Banana</button>
<button type="button" class="btn" id="PearBTN">Pear</button>
Note: I've simplified some of your CSS as well in the above example. When specifying a color where the three sets of hex digits are the same, you can specify one character for each of the three parts (i.e. #ffffff became #fff). In addition, when specifying a value of 0 there is no need to specify a unit so border-radius: 0px became border-radius: 0. Finally, when all of your padding values are the same such as padding: 2px 2px 2px 2px; you can simplify this to padding: 2px;.

I'd personally drop the jQ fanciness and class assignment and just go native.
HTML Sample:
<input type="radio" id="_set1_allclear" disabled hidden name="_set1" />
<input type="radio" disabled hidden name="_set1" />
<button type="button" onclick="if(document.getElementById('_set1_allclear').checked){ this.previousElementSibling.checked=true; callApple();}">Apple</button>
<input type="radio" disabled hidden name="_set1" />
<button type="button" onclick="if(document.getElementById('_set1_allclear').checked){ this.previousElementSibling.checked=true; callOrange();}">Orange</button>
From there, you can style the buttons via this CSS:
button { /*default button style*/ }
#_set1_allclear ~ button { /*inactive button style*/ }
:checked + button { /*active button style*/ }
All you have to do to full get this setup to work is add at the end of each of your callFruit() functions a document.getElementById('_set1_allclear').checked=true;
You could also throw that into the onclicks if you wanted to.
EDIT: Forgot to actually lock, rather than just providing the lock-trading mechanism. Woops.

Related

How to show the id of the button when hover over it

Using the following code I can change the name of the button when user hovers over it. Is there a way to change the button's name with its id when user hovers over it (using JavaScript)?
.button:hover span {
display: none
}
.button:hover:before {
content: "New name";
}
.button:hover {
background-color: #aaaaaa;
}
<button class="button" id="some_id">
<span>old name</span>
</button>
You can use attr(id). See the documentation for further information.
.button:hover span {
display: none
}
.button:hover:before {
content: attr(id);
}
.button:hover {
background-color: #aaaaaa;
}
<button class="button" id="some_id">
<span>old name</span>
</button>
Here's one that changes things back...
onmouseover="this.innerHTML=this.id;"
onmouseout="this.id=this.innerHTML; this.innerHTML='old name';"
Just add these events to the button.
Quite easy actually...
onmouseover="this.innerHTML=this.id;"
Just add this event to the button.

How to run Jscript without postback

I'm trying to build an "accordion" style collapsible div into my web page as described here on w3c schools...
accordion description
I've got most of it working - my code is this:
ASP:
<div class="col-md-4">
<button class="accordion">Section 1</button>
<div class="content">
<asp:Table ID="Consumable_table" runat="server">
<asp:TableHeaderRow>
<asp:TableHeaderCell>
<h2>
<u>Consumable Stock</u>
</h2>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</div>
</div>
CSS:
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;}
.active, .accordion:hover {
background-color: #ccc;}
.content {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;}
And I've added the following Jscript:
$(document).ready(function () {
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
return false;
});
}
});
The code seems to work fine and when I click the Accordion element it expands - But it then seems to post back and the accordion collapses again and doesn't display.
My question is how can I have it expand and stay expanded as described in the tutorial. I've seen a number of answers here and on various sites that suggests "return false" might be enough.
Does this have anything to do with the ASP table inside the div?
The dafault behaviour of the HTML button is to submit the form when clicked (its type is submit by default). All you need to do is to add type="button" attribute to the element, like this:
<button class="accordion" type="button">Section 1</button>
That should resolve the problem - it indicates that the button is just a simple clickable button, without any special action.
This answer also covers it: <button> vs. <input type="button" />. Which to use?
There are two ways,
By default the button behavior like submit button so postback will happen. If you want to prevent postback you can use below code.
<button class="accordion" onclick="return false;">Section 1</button>
You can use type attribute to prevent submit behavior.
<button type="button" class="accordion">Section 1</button>

On button click display list items, dropdown list should not hide until button is clicked again

I have looked everywhere possible as I am trying to develop a drop down button, but instead of options then the buttons display unordered list items, but when a user click off the button the the button does not close, but in order to close the button, then the button needs to be click again.
Down below you will find the way the button is when not clicked and the way the button appears when it has been clicked.
If you also go to the following website you will see an example of the button in action by click "See our list of websites"
Button on a website for example
Any help would be greatly appreciated and thanks in advance.
Here you go, key functions I used;
.click() for the a tag or the link, the function inside the .click() will be called.
.slideToggle() the ul after the click, this would hide or show the target element depending on its state.
Then add positon:absolute to the ul so that it wouldn't affect inline elements.
$(document).ready(function() {
$(".toggle-button").click(function() {
$(this).parent().find("ul").slideToggle(function() {
// Animation complete.
});
});
})
.links-unordered {
display: inline-block;
position: relative;
}
.links-unordered {
margin-top: 20px;
min-height: 30px;
}
.links-unordered .toggle-button {
text-decoration: none;
padding: 12px 16px 12px 16px;
transition: 0.2s;
border: 1px solid black;
}
.links-unordered .toggle-button:hover,
.links-unordered .toggle-button:active,
.links-unordered .toggle-button:focus,
.links-unordered .toggle-button:visited {
text-decoration: none;
color: black;
}
.links-unordered .toggle-button:hover {
border-width: 2px;
}
.links-unordered ul {
position: absolute;
top: 10px;
margin-top: 25px;
padding-inline-start: 20px;
}
.links-unordered ul li {
line-height: 25px;
padding-left: 15px;
}
.links-unordered a {
text-decoration: none;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links-unordered">
<a class="toggle-button" href="#">SEE OUR LIST OF WEBSITES</a>
<ul style="display:none;">
<li>cdn.sc.rockstargames.com</li>
<li>lifeinvader.com</li>
<li>rockstargames.com</li>
<li>socialclub.rockstargames.com</li>
</ul>
</div>
<div class="links-unordered">
<a class="toggle-button" href="#">SEE OUR LIST OF WEBSITES</a>
<ul style="display:none;">
<li>cdn.sc.rockstargames.com</li>
<li>lifeinvader.com</li>
<li>rockstargames.com</li>
<li>socialclub.rockstargames.com</li>
</ul>
</div>
I'm not sure if I understand what you want. But here's a sample of what you asked, a button that when you click, show a list. And when you click on an item, the list goes out and you have the item. Hope this helps you. It's a simple code, but if you have questions, go ahead and ask!!
function closeList(e) {
var site = e.target.innerText;
alert(site + ' clicked!!');
document.querySelector('#dvSites').style.display = 'none';
}
function showList() {
var dvSites = document.querySelector('#dvSites');
if (dvSites.style.display === '')
return; // already visible
dvSites.style.display = '';
}
// Add eventListener to close the div
var lis = document.querySelector('#dvSites').querySelectorAll('li');
for(var i = 0; i < lis.length; i++) {
lis[i].addEventListener('click', closeList);
}
// Add eventListener to open the div
document.querySelector('#btnShow').addEventListener('click', showList);
<button id="btnShow">Show sites!!</button>
<div id="dvSites" style="display: none">
<ul>
<li>stackoverflow.com</li>
<li>www.google.com</li>
<li>www.sipmann.com</li> <!-- :) -->
</ul>
</div>

Change button colour

My idea is to show an image on a map as soon as I press a button. I would like to change the colour of the button after it has been clicked and it should stay that colour until I deselect the button. The colour of the button should then change back to its original colour.
Here is the code for the button:
<button type="button" class="Button" id="tram7" class="deselected"> Tramlinie 7 </button>
And here is the function that inserts an image to the map:
$('#tram7')[0].onclick = function() {
if (overlayTram7.getMap() == map) {
$('#tram7').addClass('deselected');
overlayTram7.setMap(null);
} else {
$('#tram7').removeClass('deselected');
overlayTram7.setMap(map);
}
};
The style change worked with a hover, but I don't know how to change the style of a clicked button.
.Button {
font-family: Calibri, sans-serif;
font-size:13px;
font-weight: bold;
width: 160px;
height: 25px;
background:grey;
color: white
}
.Button:hover {
color: white;
background:green
}
Thanks in advance.
Your question isn't too clear for me. Are you wanting to change the color ONLY while the user is clicking on the button? If so, that's pretty easy, just with CSS:
You'll want the psuedo-selector, :active
.Button:active {
color: white;
background:green
}
Here is an example
Update: You clarified that you want the button's color to be changed after being clicked. Essentially acting like a toggle. Luckily JQuery has a simple solution for you: toggleClass()
Updated example using toggleClass()
The :active pseudo-selector should be what you're looking for
.Button:active {
color: white;
background:red;
}
Use toggleClass in your click callback to add/remove a class which will style your button:
$('#tram7').toggleClass('clicked');
And the class:
.Button.clicked {
color: white;
background:blue
}
http://jsfiddle.net/5m9h6/1/

Advice about my jQuery script + compatibility with iDevices

I posted a question about a script but I have another question about another script.
I have two blue buttons at the beginning that turn gray on a roll-over.
Blue becomes (and remains) gray when you click on one of the two buttons.
Both buttons must not be blue both. Each button brings up a form at a time (form contact and form quotation).
I have wrote this and I would to know if I can simplify it ?
How to make the "toggle" function compatible with iDevices (iPad, iPhone...) ?
Thank you in advance.
$(function() {
$("#form-contact").hide();
$("#form-devis").hide();
$("#btn-contact").click(function(){
$(this).toggleClass("btn-form-hover");
$("#form-contact").fadeToggle(500, "linear");
$("#form-devis").hide();
$("#btn-devis").removeClass("btn-form-hover");
});
$("#btn-devis").click(function(){
$(this).toggleClass("btn-form-hover");
$("#form-devis").fadeToggle(500, "linear");
$("#form-contact").hide();
$("#btn-contact").removeClass("btn-form-hover");
});
});
This looks about as simple as you can get for forcing only one button to have the "selected" state. If you need to do this for many elements, see my code below.
Toggle should work on iDevices as long as the jQuery library you included supports it. However, you will not get a hover effect on iDevices since there is no mouse.
Code Example:
If you plan to do this frequently with buttons (rocker switches) where only one element can have the "selected" state you could make a function like this:
CodePen: http://codepen.io/Skrypt/pen/dyCha
HTML
<div class="rockerSwitch myRocker1">
<button class="left">On</button><button class="right">Off</button>
</div>
<div class="rockerSwitch myRocker2">
<button class="left">True</button><button class="right">False</button>
</div>
<div class="rockerSwitch myRocker3">
<button class="left">Option 1</button><button class="right">Option 2</button>
</div>
CSS
.rockerSwitch button {
background-color: #dcffb2;
border: 1px solid #87cf30;
cursor: pointer;
outline: 0;
}
.rockerSwitch button.left {
margin-right: 0px;
border-radius: 5px 0px 0px 5px;
}
.rockerSwitch button.right {
margin-left: 0px;
border-radius: 0px 5px 5px 0px;
}
.rockerSwitch button:hover {
background-color: #fff;
}
.rockerSwitch button.selected {
background-color: #87cf30;
}
JS/jQuery
$(function() {
$('.myRocker1').rockerSwitch();
$('.myRocker2').rockerSwitch();
$('.myRocker3').rockerSwitch();
});
$.fn.rockerSwitch = function() {
var left = $('.left', this);
var right = $('.right', this);
left.on('click', function() {
left.addClass("selected");
right.removeClass("selected");
});
right.on('click', function() {
right.addClass("selected");
left.removeClass("selected");
});
}

Categories

Resources