Why can I only change the css style once in javascript? - javascript

I want to be able to change the backgroundColor of a box between multiple colors using js but I cannot seem to find a way. Is it possible?
window.onload = function() {
var example=document.getElementById("example");
var click=0;
example.addEventListener("click", func);
function func(){
if (click===0){
example.style.backgroundColor=("red");
click=1;
}
if (click===1){
example.style.backgroundColor=("blue");}
click=0;
}
}

Your code checks to see if the value is zero. When it is, it sets it to one. Right after that if statement you see if it is one and set it back to zero.
You need to use else if or just else so it does not evaluate the next if statement.
function func(){
if (click === 0){
example.style.backgroundColor = "red";
click = 1;
}
//else if (click === 1) {
else {
example.style.backgroundColor = "blue";
click = 0;
}
}
Personally I would just toggle a class
var elem = document.querySelector("#test")
elem.addEventListener("click", function () {
elem.classList.toggle("on");
});
div.example {
background-color: blue;
}
div.example.on {
background-color: lime;
}
<div id="test" class="example">Click Me</div>

Related

Why aren't my styles being applied when the input has a value?

Am validating HTML 5 textbox. if value is not present while submitting the form, i just want to highlight that textbox borederColor to red. if value is present, i want to go with default behavior of the text box.
Please find my code below. Am able to show the borderColor as red if value is not present. But, am not able to reset the default behavior of textbox (like default bordercolor) when value is present in the textbox. Am not sure, what is going wrong here.
var check = document.getElementById('first_name').value;
if ( check == "") {
document.getElementById('first_name').style.borderColor = "red";
} else {
document.getElementById('first_name').style.borderColor = "#eee";
}
Try this :)
var check = document.getElementById('first_name').value;
if (check == "") {
document.getElementById('first_name').style.borderColor = "red";
} else {
document.getElementById('first_name').style.borderColor = "initial";
}
}
You don't even need JS for this
<style>/*only need one of these for all your inputs*/
input:invalid {
border: 2px solid red;
}
</style>
<input type="text" required/>
Further reading at https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
You need to bind an event listener onchange
var el = document.getElementById('first_name');
el.addEventListener('onchange', function(){
var check = document.getElementById('first_name').value;
if ( check == "") {
document.getElementById('first_name').style.borderColor = "red";
} else {
document.getElementById('first_name').style.borderColor = "#eee";
}
})
Only following code is working for me.
var check = document.getElementById('first_name').value;
if (check == "") {
document.getElementById('first_name').style.borderColor = "red";
} else {
document.getElementById('first_name').style.borderColor = "";
}
}

Click to change element color

I wrote this little script to change a class color on click, it works, but i would to restore the primary color with a second click.
function changeColor1() {
document.getElementById("ip-custom").className = "red";
}
function init() {
document.getElementById("ip-custom").onclick = changeColor1;
}
window.onload = init();
.red {
color: #f00;
}
<button id="ip-custom">Example</button>
You can toggle class red like following.
function changeColor1() {
document.getElementById("ip-custom").classList.toggle('red');
}
Full snippet
function changeColor1() {
document.getElementById("ip-custom").classList.toggle('red');
}
function init() {
document.getElementById("ip-custom").onclick = changeColor1;
}
window.onload = init();
.red {
color: #f00;
}
<button id="ip-custom">Example</button>
If you want to use plain js use the classList.toggle function:
function changeColor1() {
document.getElementById("ip-custom").classList.toggle('red');
}
If you use jQuery you can use the toggleClass function:
function changeColor1() {
$("#ip-custom").toggleClass("red");
}
classList documentation
toggleClass documentation
Since you have included the tag jquery, I'll provide an answer using that and plain old javascript.
JavaScript
Check for the existence of the class to determine if you should then add or remove it.
function changeColor1() {
if (document.getElementById("ip-custom").className == "red")
document.getElementById("ip-custom").className = "";
else
document.getElementById("ip-custom").className = "red";
}
function init() {
document.getElementById("ip-custom").onclick = changeColor1;
}
window.onload = init();
.red {
color: #f00;
}
<button id="ip-custom">Example</button>
jQuery
You can make use of jQuery's toggleClass() method.
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
$(function() {
$('#ip-custom').on('click', function() {
$(this).toggleClass('red');
});
});
.red {
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="ip-custom">Example</button>
This solutions only works in your case, when element has no class.
So, it add red class o remove all clasess;
function toggleClassRed() {
var element = document.getElementById("ip-custom"),
clazz = element.className || '';
element.className = clazz === '' ? 'red' : '';
}
function init() {
document.getElementById("ip-custom").onclick = toggleClassRed;
}
window.onload = init();
.red {
color: #f00;
}
<button id="ip-custom">Example</button>
You have a simple solution to save the state in a variable.
var clicked = false;
function changeColor1() {
if(!clicked){
document.getElementById("ip-custom").className = "red";
clicked = true;
}else{
document.getElementById("ip-custom").className = "";
clicked = false;
}
}

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

jQuery mouseenter functions - changing colour if colour isn't already

So, I am not that fluent with jQuery and I have written a bit of code in it that doesn't look as if it works. Here is my code;
$(document).ready(function() {
$("#loginSelector").mouseenter(function() {
if $("#loginSelector").style.backgroundColor != "#3064CA" {
$("#loginSelector").style.backgroundColor = "#3064CA";
};
});
$("#loginSelector").mouseleave(function() {
if $("#loginSelector").style.backgroundColor != "#5990DE" {
$("#loginSelector").style.backgroundColor = "#5990DE";
};
});
$("#signupSelector").mouseenter(function() {
if $("#signupSelector").style.backgroundColor != "#3064CA" {
$("#signupSelector").style.backgroundColor = "#3064CA";
};
});
$("#signupSelector").mouseleave(function() {
if $("#signupSelector").style.backgroundColor != "#5990DE" {
$("#signupSelector").style.backgroundColor = "#5990DE";
};
});
});
All I want the code to do is check to see if the button is not a certain colour, and if it isn't that colour and it is hovered on, it changes to another colour.
Try this and follow the same for the rest of the blocks.
$("#loginSelector").mouseenter(function() { //when hovered on
var desiredColor = "#3064CA"; //define the desired color
if ( $(this).css('color') === desiredColor) return; //if the element's color = the desired color, don't do anything. stop the execution
$(this).css('color', desiredColor); //else set the desired color
});
Assuming the elements initially have the color #5990DE, I'd simply add the following css:
#loginSelector, #signupSelector{
background: #5990DE;
}
#loginSelector:hover, #signupSelector:hover{
background: #3064CA;
}
Or if otherwise,
css:
.onHover{
background: #3064CA;
}
.onLeave{
background: #5990DE;
}
script:
$(document).on('mouseenter', 'loginSelector , #signupSelector', function(){
$(this).addClass('onHover').removeClass('onLeave');
});
$(document).on('mouseleave', '#loginSelector , #signupSelector', function(){
$(this).addClass('onLeave').removeClass('onHover');
});

How to add js var inside jquery

Somehow I can't make the var "turn" change.
--------------'#a3' is a div-----------------
For all of the code go here.
Here is some of the js/jquery:
var turn = 1;
if (turn === 1) {
//----------------------------red
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "red");
turn = 0;
});
}
if (turn === 0) {
//----------------------------blue
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "blue");
turn = 1;
});
}
Here is some css I used:
div {
display: inline-block;
background-color:grey;
width : 150px;
height: 150px;
}
It is because you only add one event handler that only does one thing. It is not magically going to add the other one.
Do the if/else logic inside of the click events.
If you want to toggle the background-color by clicking the a3-element, you need to do the if/else checking inside of the event-handler:
bg_state = 0;
$('#a3').click(function () {
if (bg_state===0) {
$(this).css("background-color", "blue");
bg_state=1;
} else {
$(this).css("background-color", "red");
bg_state=0;
}
});
http://jsfiddle.net/ADUV9/
The setting of the event-handler is only executed one time, when the page loads!
Your current code is structured like this:
var turn = 1; // red turn first
if (turn === 1) {
// assign click handlers for red moves
}
if (turn === 0) {
// assign click handlers for blue moves
}
The problem with this is that the only click handlers that will ever be used here are the ones defined in the if (turn === 1) block. The code will not be re-evaluated when you modify turn so the click handlers for blue will never be used.
Instead it should look something like this:
var turn = 1; // red turn first
// example click handler:
$('#a3').click(function () {
// check whose turn it is *inside* of the click handler
if (turn === 0) {
$(this).css("background-color", "blue");
turn = 1;
} else {
$(this).css("background-color", "red");
turn = 0;
}
});
// other click handlers like the above (or better yet, reuse the same function)

Categories