I'm trying to keep the selected button active after the button is clicked, which changes the page. My current setup is
HTML:
<a class="btn btn-default nav" id="btn" type="button" href="index.php?mode=option">Option</a>
JS:
$(function() {
//Variable of previously selected
var selected = [];
//Setup Buttons
$('.nav').button().click(function() {
//Enable previous
if(selected[0]) {
selected.button('enable').removeClass('active');
}
//Cache the previous
selected = $(this);
//Disable this and keep color attributes
selected.button('disable').addClass('active');
//Do Normal Button Click Stuff Here
$('#data').text(selected.text() + ' was clicked');
});
$('#btn').click();
});
Currently all this does is the button Option is active, I click another, it changes to active but then it goes back to Option being active.
I'd also like to be able to use this JS without having to have nav in the class of the button.
Related
I am in a situation that the user is presented with many different buttons.
When any button is clicked, a different form is spawned and a string is injected in the dom to notify the user which form is pressed.
Pseudocode:
<div id="notifier">
<h1 class="text-center">
<> SOMETHING SHOULD GO HERE<>
<script>
$(document).ready(function(){
$("#notifier").hide(); //hide the initial string since no form is pressed at the beginning
$("#editForm1").hide(); //hides form1 since no button is pressed
$("#editForm2").hide(); //hides form2 since no button is pressed
$("#btn_1").click(function(e) {
//SOMETHING SHOULD GO HERE AS WELL
$("#editForm1").show();
When button1 is pressed, form1 is spawned in the dom.
But i also want to inject the string "Form1" inside the div with id="notifier", to let the user know which form is spawned.
How do i do that?
Use the data-* attribute to store the target selector: data-formshow="#form-1"
Use a CSS class to hide your forms: .none { display: none; }
Use jQuery to select your buttons and forms
Use jQuery .addClass() and .removeClass() to manipulate the .none class
Use .not() to exclude specific Elements from a collection:
jQuery($ => {
const $notifier = $('#notifier'); // the <H1>
const $buttons = $('[data-showform]'); // the <button>s
const $forms = $('[id^="form-"]'); // the <form>s
$buttons.on('click', function(ev) {
ev.preventDefault();
const sel = $(this).data('showform'); // Get the selector
const txt = $(this).text(); // Get the text
const $form = $(sel); // Get the form Element
$forms.not($form).addClass('hide'); // Hide other forms
$form.removeClass('hide'); // Show target form
$notifier.text( txt ); // Preview button text into H1
});
});
.hide { display: none; }
<h1 id="notifier">CLICK A BUTTON</h1>
<button type="button" data-showform="#form-1">FORM ONE</button>
<button type="button" data-showform="#form-2">FORM TWO</button>
<form id="form-1" class="hide">I'm form ONE</form>
<form id="form-2" class="hide">I'm form TWO</form>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
I'm having troubles with my javascript code, I have a snippet that creates a number of button depending on the loop range, the buttons share the same class but the ids are different
<div class="panel-footer" id="loop">
<ul class="post-action">
{% for i in range %}
<button class="btn btn-success guess" id="{{ i }}" value="{{ i }}" onclick="transferField(this.value)">{{ i }} </button>
{% endfor %}
</ul>
</div>
I am trying to change the color of each button when it is clicked and when clicked again changes back to default color but its not working fine, when i click on button 5 it changes color but once i click on button 6, it wont change color until i click button 6 or click another button again. Here is the js code:
<script>
clicked = true;
$(".guess").click(function(){
xyz = this.id
console.log(xyz)
if(clicked){
$('#' + this.id).css('background-color', '#FF8E2B');
clicked = false;
} else {
$('#' + this.id).css('background-color', '#27AE60');
clicked = true;
}
});
</script>
What have i done wrong?
Your problem is you are using clicked as a global variable.
Just store clicked in this.
$(".guess").click(function(){
xyz = this.id
console.log(xyz)
if(this.clicked){
$(this).css('background-color', '#FF8E2B');
this.clicked = false;
} else {
$(this).css('background-color', '#27AE60');
this.clicked = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-footer" id="loop">
<ul class="post-action">
<button class="btn btn-success guess" id="one" value="one" > one</button>
<button class="btn btn-success guess" id="two" value="two" > two</button>
<button class="btn btn-success guess" id="three" value="three" > three</button>
</ul>
</div>
You are trying to "track" the state of multiple buttons using a single var, of course this wont work
try the following instead
$(".guess").click(function(){
var $this = $(this);
var clicked = $this.data('clicked');
if(clicked) {
$this.css('background-color', '#FF8E2B');
} else {
$this.css('background-color', '#27AE60');
}
$this.data('clicked', !clicked);
});
You can store an array of color for each element at data-* of element, use .data(), Array.prototype.reverse() to toggle to array, set background to element at index 0 of array
$("button").on("click", function() {
$(this).css("background", $(this).data().colors.reverse()[0])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-colors='["#FF8E2B", "#27AE60"]' style="background:#FF8E2B">click</button>
What have i done wrong?
The main issue you have with your code is that you have one variable keeping track of the clicked state of multiple button elements.
The way to fix this is to add state to the element itself essentially giving multiple variables for multiple elements.
I'm doing this by adding an event object to the callback of the click handler and getting event.currentTarget. The value of event.currentTarget is the element object being clicked. You can add state to this object just like you'd add state to another other javascript object
event.currentTarget.clicked = true;
Now you can keep track of the state for each element!
// just some simple code to get your template in pure JS, don't worry about the code here
const range = [0,1,2,3,4,5];
const template = `<div class="panel-footer" id="loop">
<ul class="post-action">
${range.map(i => `
<button class="btn btn-success guess" id="${i}" value="${i}">${i}</button>
`)}
</ul>
</div>`;
const div = document.createElement('div');
div.innerHTML = template;
document.body.appendChild(div);
// here are where the changes start
// var clicked = true; instead of having a global variable to keep track of the state of all your buttons
$(".guess").click(function(event) {
// you need local state attached to the button
// here we're getting the button element being clicked
const currentTarget = event.currentTarget;
xyz = this.id
console.log(xyz);
// if clicked is truthy
if (currentTarget.clicked) {
$('#' + this.id).css('background-color', '#FF8E2B');
currentTarget.clicked = false;
} else {
$('#' + this.id).css('background-color', '#27AE60');
// set on the element some state
currentTarget.clicked = true;
}
});
.guess {
/* start out in the orange state */
background-color: #FF8E2B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How do I "reset" the .replaceWith function so that the html, css and javascript are returned back to their original state?
The idea is to have an icon replace the text when the user clicks on "contact", and when the user clicks on "back" button, the icon returns back to the "contact" text. Right now, the icon switches back to text, but the text isn't responsive when I try to repeat the function a second time.
Here is the HTML:
<div class="contact">Contact</div>
<button class="back">Back</button>
And the Javascript:
var contactswitch = $('<div class="icon"><i class="fa fa-facebook"></i></div>');
var switchback = $('.contact');
$('.contact').click(function() {
$(this).replaceWith(contactswitch)
});
$('.back').click(function() {
$(contactswitch).replaceWith(switchback)
});
Thanks!
I think you need to re-assign the click handler on the back button click:
$('.back').click(function() {
switchback.click(function() { $(this).replaceWith(contactswitch);});
$(contactswitch).replaceWith(switchback)
});
I have created a 3 x 2 grid of squareish buttons that are monotone in colour. I have a slidetoggle div that pops down inbetween both rows of 3 and as it does so it pushes the content down of the rest of hte page, this is all working perfectly so far.
But i have made a class (.active) thats css is the same as the :hover state so that when i hover over a button the coloured version replaces the monotone version, however i have tried to add some js to make the colour (.active) stay on once i have clicked on a certain button so that you can see which button (product) the slidedown div relates to and the rest are still in monotone around it...
The .active code below works perfectly to turn the bottons colour on and off when you click that one button, but i have set it up so that if one button's div is open and you click on a different one, the open one closes and then the new one opens. This feature however throws off the balance of the code i have for the .active state here. When you have say button 1 open and you click button 1 to close, this works fine, the color goes on and then off, but if yo uhave button 1 open and click on button 2, button 1's div closes and opens button 2's div but then botton 1 stays in colour as button 2 turns to colour. the order is thrown off...
I need to add some js to say, that only one button can be in color (.active) at a time, or that if one is .active it must be turned off before the new one is turned on... Please help :)
$(document).ready(function(){
$("a.active").removeClass('active'); //<<this .active code &
$("#product1").click(function(){
if($(this).parent('a').hasClass('active')){ //<<<this .active code
$(this).parent('a').removeClass('active'); //<<
}else{ //<<
$(this).parent('a').addClass('active'); //<<
} //<<
$("#product2box").slideUp('slow', function() {
$("#product3box").slideUp('slow', function() {
$("#product4box").slideUp('slow', function() {
$("#product5box").slideUp('slow', function() {
$("#product6box").slideUp('slow', function() {
$("#product1box").stop().slideToggle(1000);
//do i need
//something here??
});
});
});
});
});
});
And here is the HTML
<div id="row1">
<a href="#!" class="active"><span id="product1">
<div id="productblueheader">
<div id="productlogosblue1"></div>
</div>
<div id="productstitle">Stops all spam and unwanted email.</div>
<div id="producttext">With over 8 million users ******* is the leading in anit-spam software on the market today! Sort all your spam issues in one place now!</div>
</span></a>
<a href="#!" class="active"><span id="product2">
<div id="productblueheader">
<div id="productlogosblue2"></div>
</div>
<div id="productstitle">The easiest email encryption ever.</div>
<div id="producttext">In todays world, we won’t enter personal details in to untrusted websites, but we send personal information via regular (insecure) email all the time.</div>
</span></a>
<a href="#!" class="active"><span id="product3">
<div id="productblueheader">
<div id="productlogosblue3"></div>
</div>
<div id="productstitle">The easiest email encryption ever.</div>
<div id="producttext">****** is a revelation in security and ease of use. Get the best protection against viruses, spyware, scam websites and other threats.</div>
</span></a>
</div>
(then the same for row2 products 4-6)
you use .each() method of jquery and find .active class to remove it,
and then add .active class.
$(this).parent('a').each(function(){
$(this).removeClass('active');
});
$(this).parent('a').addClass('active');
This ought to work, but I couldn't test it without the relevant HTML:
$(document).ready(function () {
$("#product1").click(function () {
$("a.active").removeClass('active');
$(this).parent('a').toggleClass('active'));
$("#product2box").slideUp('slow', function () {
$("#product3box").slideUp('slow', function () {
$("#product4box").slideUp('slow', function () {
$("#product5box").slideUp('slow', function () {
$("#product6box").slideUp('slow', function () {
$("#product1box").stop().slideToggle(1000);
});
});
});
});
});
});
});
Also, there would probably be a better way to write all those sliding up functions. Do they really need to go on by one by the way?
$(document).ready(function() {
$(".producthandler").click(function() {
var ctx = $(this);
var productboxId = ctx.children().eq(0).attr("id");
ctx.toggleClass('active');
$("#" + productboxId + "box").stop().slideToggle(1000);
$(".producthandler").each(function() {
var ctx = $(this);
var producthandlerId = ctx.children().eq(0).attr('id');
if (productboxId !== producthandlerId) {
ctx.removeClass('active');
$("#" + producthandlerId + "box").slideUp(1000);
}
});
});
});
--EDIT--
I have the toggle Button with which slides left and right. The toggle and animation are working fine, but the problem comes when adding more than one instance of toggle button on the same page. When I click on a toggle button, All the toggle buttons are using the same VAR. So if you open one and then click another one, the second one doesn't slide open because it thinks is suppose to close. Where would you put the isChecked var so that it is different for each instance?
js fiddle
http://jsfiddle.net/amQCN/11/
$(document).ready(function() {
var isChecked = false;
$('.toggle-radio-switch').click(function() {
if (isChecked == true) {
$(this).find('.radio-switch-slider').animate({'margin-left': '0px'},'150');
isChecked = false;
console.log("isChecked = " + isChecked);
} else {
$(this).find('.radio-switch-slider').animate({'margin-left': '34px'},'150');
isChecked = true;
console.log("isChecked = " + isChecked);
};
});
});
radio-switch-slider is positioned on top of the contents and slides back and forth revealing yes or no
<div class="toggle-radio-switch" id="toggle3">
<span>yes</span>
<span>no</span>
<div class="radio-switch-slider"></div>
</div>
Working version incase anyone is wondering:
Ended up just using this instead
$('.toggle-radio-switch').click(function() {
if ($(this).find('.radio-switch-slider').css('margin-left')=="0px"){
$(this).find('.radio-switch-slider').animate({'margin-left': '34px'},'150');
} else {
$(this).find('.radio-switch-slider').animate({'margin-left': '0px'},'150');
}
});
I'm betting your .toggle-radio-switch elements are siblings. Remove .parent() from your code. It isn't needed since .radio-switch-slider is contained directly in .toggle-radio-switch
$(this).find('.radio-switch-slider')...