Button Background Color change - javascript

I have 4 buttons(B1,B2,B3,B4) in HEADER section,Each button redirects to different page in the same tab.
Button background color is WHITE.
Whenever I clicked on specific button, entire page will reload and redirects to specific button page.
NOTE: Header section is included in all 4 button pages.
Now my requirement is :
Whenever I click on specific button, that specific button back ground color only should change to another color(say ex: RED) rest showld be WHITE color only.
EX: If i click B1 button, page should reload, then back ground color of B1 button should change to RED rest should be WHITE.
How to do this in Jquery or Java script or CSS?
Pls. assist me.
.HeaderButtons {
width: 15%;
background-color: WHITE;
}
<div id="Header">
<input type="button" name="B1" id="B1" value="B1" class="HeaderButtons">
<input type="button" name="B2" id="B2" value="B2" class="HeaderButtons">
<input type="button" name="B3" id="B3" value="B3" class="HeaderButtons">
<input type="button" name="B4" id="B4" value="B4" class="HeaderButtons">
</div>

It sounds like your trying to set an active state on button based on the URL, using a slight change on this article to use buttons rather than links https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/
<div id="Header">
<input data-href="/" type="button" name="B1" id="B1" value="B1" class="HeaderButtons">
<input data-href="/page1/" type="button" name="B2" id="B2" value="B2" class="HeaderButtons">
<input data-href="/page2/" type="button" name="B3" id="B3" value="B3" class="HeaderButtons">
<input data-href="/page3/" type="button" name="B4" id="B4" value="B4" class="HeaderButtons">
</div>
<script>
//jQuery code that adds active class to the button that has the URL path as its data-href attribute
$(function() {
$('input[data-href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
</script>
.HeaderButtons.active {
background-color: RED; //CSS to change the button color
}

Best approach is to use AJAX. Otherwise if you are reloading the entire page, the clicked button you may have to store it into somewhere like session or db(Which is not a good practice) or pass through the url like page.php?id=b1.
CSS:
.HeaderButtons
{
width:15%;
background-color:WHITE;
}
.HeaderButtonsRed {
background-color:red !important;
}
JS:
$(document).ready(function(){
$(".HeaderButtons").click(function () {
if ($(this).hasClass('HeaderButtonsRed')) {
$(this).removeClass('HeaderButtonsRed');
} else {
$(".HeaderButtons").removeClass('HeaderButtonsRed');
$(this).addClass('HeaderButtonsRed');
}
});
});

I think if the page redirects/refresh than U cant achive using pure css nither you can do it without adding parameters to URL as discribed in other comments
But you can give a try on cookies, I havent tried applying it but you can try it using jQuery cookie plugin.
$('.b1').click(function(){
var clicks = $(this).data('clicks');
if(clicks && $.cookie("yourcookiename")=='')
{
$.cookie("yourcookiename","yourcookieval");
// $('.b1').css('background-color','red'); then redirect page code
}
else
{
// $.removeCookie("yourcookiename"); & then $('.b1').css('background-color','white');
}
$(this).data("clicks", !clicks);
});

There are many ways to achieve this and the best method is ultimately going to depend on your application, personal taste and a wide array of other factors. Things to consider:
cookies
html localStorage
html sessionStorage
http url paramters
php sessions
Here's a method using HTML localStorage to store the button id on a click event like below. You can then fetch the value on subsequent page load/reload anywhere on the same domain indefinitely.
DEMO: http://buttons.demo.zuma-design.com/button-demo-a.html
<!DOCTYPE html>
<html>
<head>
<style>
.HeaderButtons {
width: 15%;
background-color: WHITE;
}
</style>
</head>
<body>
<div id="Header">
<input type="button" name="B1" id="B1" value="B1" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">
<input type="button" name="B2" id="B2" value="B2" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">
<input type="button" name="B3" id="B3" value="B3" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">
<input type="button" name="B4" id="B4" value="B4" class="HeaderButtons" onclick="setButton(this.id); window.location.href=window.location.href">
</div>
<script type="text/javascript">
function setButton(value) {
localStorage.setItem("buttonID", value);
}
if (localStorage.buttonID) {
document.getElementById(localStorage.buttonID).style.backgroundColor = "RED";
}
</script>
</body>
</html>

Thanks for your suggestions and answers, but the point is , I dont want script code on button click since Page will reload on click of button, hence unable to keep back ground color at that event.
I got solution ,it is a bit old, but it works for me exactly. But I need to do hard coded. If any other solutions provided will be appreciated.
Here is my Jquery/Javascript code :
$(document).ready(function ()
{
var pageURl=window.location.href;
if(pageURl.indexOf("Page1.aspx") >-1)
{
$('#B1').addClass('ButtonBackColorred');
}
if(pageURl.indexOf("{Page2.aspx") >-1)
{
$('#B2').addClass('ButtonBackColorred');
}
if(pageURl.indexOf("Page3.aspx") >-1)
{
$('#B3').addClass('ButtonBackColorred');
}
if(pageURl.indexOf("Page4") >-1)
{
$('#B4').addClass('ButtonBackColorred');
}
$('#B1').click(function()
{
window.location=".../Page1.aspx";
});
$('#B2').click(function()
{
window.location=".../Page2.aspx";
});
$('#B3').click(function()
{
window.location=".../Page3.aspx";
});
$('#B4').click(function()
{
window.location=".../Page4.aspx";
});
});

Well, this is a relatively simple piece of jquery. Here's how:
$('#*button id*').css('background-color', '#ff0000');
This is just the code for the button color change.

Related

Image tag inside a button makes the js stop working on chrome

I'm trying to make a button with an image that will toggle a div's class, however, when I use the tag image inside the button, the js won't work. This only happens on chrome, the same code works normally on firefox. Is there any solution to this?
codepen: https://codepen.io/luansergiomattos/pen/zydWyM
html:
<div class="bar" style="background-color: #474973; ">
<br />
<button id="searchButton">
<img
src="https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-512.png"
alt=""
style="width: 20px;"
/>
</button>
</div>
<div class="bar off but" id="search" style="background-color: #9CEAEF">
<form action="#">
<input
type="text"
placeholder="Search.."
name="search"
class="header__search"
/>
</form>
</div>
js:
var focused = document.querySelector('.header__search'), searchWrapper = document.querySelector('#search'),
searchInput = document.querySelector('#searchButton');
document.addEventListener('click', function (e) {
if (~e.target.className.indexOf('header__search')) {
searchWrapper.classList.remove('off');
focused.focus();
} else if (~e.target.id.indexOf('searchButton')) {
searchWrapper.classList.toggle('off');
focused.focus();
} else {
searchWrapper.classList.add('off');
}
});
edit: this is what the code is supossed to do: when i press the button, the js will toggle a class, the class named "off" has width: 0px; display: none etc. So the element will be hidden when i press the button, and it will show up again when i press the button. Sorry for any english mistak
The reason this happens is the image becomes the target in your click function – try disable pointer events and it will work again :)
button img { pointer-events: none; }

1 Form, 2 Divs, JQuery not working

I have a form that contains 2 divs, and in each div is an input, and when I press the buttons associated with each input, nothing happens and I believe it has something to do with the divs in the form. I know this code works when there wasn't the 2 divs, but I need to the divs so I can have the layout the way it is. Any suggestions?
I know I'd forgotten to add JQuery to this post, it was my mistake, but even with JQuery added it wasn't working in my project, in which this code is based.
Live code: https://jsfiddle.net/1brk3npL/
$(document).ready(function() {
$('#addLikes').click(function() {
if ($('#likes').val() === "") {
alert("Likes input is empty.");
} else {
$('#likesOutput').append($("<option></option>")
.attr("value", $('#likes').val()).text($('#likes').val()));
}
});
$('#removeLikes').click(function() {
$('#likesOutput option:selected').remove();
});
$('#addDislikes').click(function() {
if ($('#dislikes').val() === "") {
alert("Dislikes input is empty.");
} else {
$('#dislikesOutput').append($("<option></option>")
.attr("value", $('#dislikes').val()).text($('#dislikes').val()));
}
});
$('#removeDislikes').click(function() {
$('#dislikesOutput option:selected').remove();
});
});
select {
width: 250px;
}
input[type=text] {
font-family: "ProximaRegular", sans-serif;
width: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="preferenceDiv">
<form id="preferenceInput">
<div style="float:left; position:relative; width : 50%;">
Likes:
<br/>
<input type="text" id="likes" />
<br />
<button id="addLikes" type="button">Add Likes</button>
<button id="removeLikes" type="button">Remove Likes</button>
<br />Selected Likes:
<br />
<select id="likesOutput" multiple="multiple"></select>
</div>
<div style="float:left; position:relative; width : 50%;">
Dislikes:
<br/>
<input type="text" id="dislikes" />
<br />
<button id="addDislikes" type="button">Add Dislikes</button>
<button id="removeDislikes" type="button">Remove Dislikes</button>
<br />Selected Dislikes:
<br />
<select id="dislikesOutput" multiple="multiple"></select>
</div>
</form>
</div>
Ok, so the code started working as intended yesturday. I don't know what happened, I didn't change the code in anyway. But one minute it wasn't working, then suddenly it was.
Add jQuery and also add $ reference to jQuery.
Chnage the first line of the JS like this
jQuery(document).ready(function ($) {
Even if you include jQuery there is reference missing. PLease change it and it'll work.
Just Add below jquery library in this https://jsfiddle.net/1brk3npL/ HTML part and see it's working :)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Thanks
jQuery is not defined.
I just added jQuery on your jsfiddle and your code works.
Click on Javascript options -> FRAMEWORKS & EXTENSIONS -> Select jQuery version - > Click On Run

How to show and close form on click of a div?

When a div is clicked I want to show a form, as done on this page. This is what I have tried (fiddle):
$(document).on("click","#tawkchat-minified-container",function() {
var htmldynamic = ' <form id="test" action="test.php">\
<div>\
Test: <input name="blah" value="test" type="text">\
</div>\
</form>'
$("#maximizeChat").html(htmldynamic);
});
I don't know if this is the right way to do it. Is there a better approach?
Adding large chunks of HTML as JavaScript variables is not good practice. It is easy to make errors in the HTML as you have to read it awkwardly embedded in the JS.
A better approach is to include the HTML code with the rest of your markup, but use CSS to hide it. Then you can just show it using JavaScript when it is pressed.
HTML:
<div id="my-form-container">
<div id="my-form-header">My form</div>
<form id="my-form" action="test.php">
<div>
Test: <input name="blah" value="test" type="text">
</div>
</form>
</div>
CSS:
#my-form {
display: none; /* This will hide the form. */
}
JavaScript:
//When the container is clicked...
$("#my-form-container").click(function() {
//...show the form.
$("#my-form").show();
});
Use this approach will definitely solve your problem
$(document).ready(function(){
$("#tawkchat-minified-agent-container").click(function()
var hlink = $("#test").val();
$("#test").click(function(){
$(".form").show()
});
});
});

How to make a button visible by clicking another button?

How can I make the button save visible when I click the edit button? This is my code so far, but it happends nothing. I'm working in a jsp
<INPUT TYPE="BUTTON" VALUE="Edit" ONCLICK="btnEdit()" class="styled-button-2">
<INPUT TYPE="BUTTON" VALUE="Save" ONCLICK="btnSave()" class="styled-button-2" style="visibility:hidden;" id="save">
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementsById("save").style.visibility="visible";}
}
</script>
DEMO
It is considered bad practice to add onclick in your html, and you miss-spelled a method. You should equally avoid adding your css in your html as well.
HTML:
<INPUT TYPE="BUTTON" VALUE="Edit" class="styled-button-2" id="edit">
<INPUT TYPE="BUTTON" VALUE="Save" class="styled-button-2" id="save">
JS:
var edit = document.getElementById("edit");
var save = document.getElementById("save");
edit.onclick = function() {
save.style.visibility = "visible";
}
CSS:
#save {
visibility: "hidden";
}
Must be a long day.
You have a misspelling.
Not right
document.getElementsById
Right Way
document.getElementById
document.getElementById("save").style.visibility="visible";
use getElementById not getElementsById
Probably a simple error, but you wrote getElementsById not getElementById, which meant you were trying to get more than one element, when infact you only need to get the "save" button.
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementById("save").style.visibility="visible";}
}
</script>
Side note: You may want to tidy your code:
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
document.getElementById("save").style.visibility="visible";
}
</script>

Hide/unhide div with button?

<h1>Welcome! Chat now!</h1>
<button id="button">Chat Now</button>
<button id="buttontwo">Chat Categories</button>
<div id="login" style="visibility:hidden">
<button id="closelogin">Close</button>
<input type="text" placeholder="Username"/>
<p id="loginshiz">Pick a username</p>
<button id="go">Go</button>
</div>
When the chat now button is pressed, I want to make the div "login" appear, and when the "closelogin" button inside the div is pressed, I want to make the whole div hidden again. Currently if no buttons are pressed the div should be at hidden state, cheers!
Use jQuery. No way to do it plain html/css.
$('#button').click(function() {
$('#login').css('visibility', 'visible');
});
$('#closelogin').click(function() {
$('#login').css('visibility', 'hidden');
});
If you don't have jQuery included, use javascript:
document.getElementById('button').onclick = function() {
document.getElementById('login').style.visibility = 'visible';
}
document.getElementById('closelogin').onclick = function() {
document.getElementById('login').style.visibility = 'hidden';
}
Look at my example without using of JavaScript.
<input type="checkbox" id="box"/>
<label id="container" for="box">
<div id="button">Chat Now</div>
<div id="login">
<label for="box" id="closelogin">Close</label>
<input type="text" placeholder="Username"/>
<p id="loginshiz">Pick a username</p>
<button id="go">Go</button>
</div>
</label>
and css
#box{display: none;}
#container #login{ display: none;}
#box:checked + #container #login{ display: block;}
Fiddle http://jsfiddle.net/LUdyb/1/
Hope this help.
Using javascript with the help of the button id you can make the div to be hidden by changing the css property to visible. while using jquery you can use toggle,hide,show.
There is no way you can do this in html/css
You can use Jquery
$('#button').click(function() {
$('#login').css('visibility', 'visible');
});
to close
$('#closelogin').click(function() {
$('#login').css('visibility', 'hidden');
});
you just need to change the ID that is #closelogin and the .css('visibility', 'hidden')
You need to include Jquery library like this in your head or bottom of your page to make it work.
eg:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Categories