Click to change element color - javascript

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;
}
}

Related

Why can I only change the css style once in 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>

Get class name of clicked element

I have some dynamically created divs . And when the user clicks on the screen I want to check if it was on one of the dynamically created divs.But it doesnt seem to work. I already have a window.addeventListener but that too is not working for the dynamically created divs.
var divk = document.createElement("div");
divk.className="divk";
window.addEventListener('click', function(e){
if (document.getElementById('outside_click_purpose').contains(e.target)){
currentItem = e.target;
if (currentItem.classList.contains("divk")) {
alert("contains !!!");
}
}
});
I think you need to use event delegation then use matches
Notice how we use
e.target.matches('.dynamic')
To check for the presence of our class, we can use any valid css selector
For example, if we wanted to ensure it was a div:
e.target.matches('div.dynamic');
See the demonstration below:
// Add some dynamic divs
const getDiv = (content) => {
const div = document.createElement('div');
div.className = 'dynamic';
div.innerHTML = content;
return div;
};
const setMessage = (msg) => document.querySelector('.clicked').innerText = msg;
document.addEventListener('DOMContentLoaded', () => {
const container = document.querySelector('#container');
for(let i = 0; i< 10; i++) {
container.appendChild(getDiv(`Dynamic ${i}`));
}
});
// Use event delegation
document.addEventListener('click', (e) => {
if(e.target.matches('.dynamic')) {
setMessage(`Clicked a dynamic div - text ${e.target.innerText}`);
}
else {
setMessage('Click was not on dynamic');
}
});
.clicked {
height: 20px;
border: 1px solid red;
}
.manual {
background-color: blue;
color: white;
}
<div class="clicked"></div>
<div class="manual">Manual</div>
<div class="manual">Manual</div>
<div id="container"></div>

Javascript onchange validation so that :valid and :invalid CSS selectors work

This seems like a simple thing to do, but I have not been able to find anything about this.
How can I use something like the following:
// html: <input type="text" onchange="validate()">
function validate(e) {
e.preventDefault();
if(isValid(this.value)) {
// make valid somehow
} else {
// make invalid somehow
}
}
so that the following CSS works as you might expect:
input:valid {
background: green;
}
input:invalid {
background: red;
}
Click "Run code snippet" to see!
You can create a custom validator and use the setCustomValidity function on the element to allow use of these selectors.
This article describes how to use the HTML5 Constraint API to achieve this.
Example:
#inputField:valid {
background-color: green;
}
#inputField:invalid {
background-color: red;
}
<html>
<body>
Type a value (must be 'abc'): <input id="inputField">
<script type="text/javascript">
function validateField() {
if (this.value !== 'abc') {
this.setCustomValidity('Value must be abc!');
}
else {
this.setCustomValidity('');
}
}
window.onload = function () {
document.getElementById("inputField").oninput= validateField;
}
</script>
</body>
</html>
function validateField(event) {
event.preventDefault();
var target = event.currentTarget
if (target.value != "" || target.value.length > 0) {
target.classList.remove("invalidFunction");
target.classList.add("validFunction");
} else {
target.classList.add("invalidFunction");
target.classList.remove("validFunction");
}
};
.invalidFunction {
border-color: red;
}
.validFunction{
border-color: green;
}
Field is mandatory:
<input id="inputFunctionField" onchange="validateField(event)">
you can just use css classes if you wish (and I added the syntax for using jquery to addclasses and remove classes but can also be done in pure javascript)..
input.valid {
background: green;
}
input.invalid {
background: red;
}
function validate(e) {
e.preventDefault();
if(isValid(this.value)) {
$(this).removeClass("invalid");
$(this).addClass("valid");
} else {
$(this).removeClass("valid");
$(this).addClass("invalid");
// make invalid somehow
}
}
none jquery (assuming there is no other classes currently used. as this seems like the html you have, if there are additional classes just manipulate the string to add and remove the relevant class).
function validate(e) {
e.preventDefault();
if(isValid(this.value)) {
this.className = "valid"
} else {
this.className = "invalid"
// make invalid somehow
}
}
Are you looking for something like this?
// html: <input type="text" onchange="validate()">
function validate(e) {
e.preventDefault();
var target = e.target
if(isValid(this.value)) {
target.classList.add("valid")
target.classList.remove("invalid")
} else {
target.classList.remove("valid")
target.classList.add("invalid")
}
}

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 do I change Background color of textbox when onfocus?

I tried this code but its not working; when I on-focus textbox it shows an error:
function ChangeBgColor(obj, evt)
{
if(evt.type=="focus")
style.background ="lightgrey";
else if(evt.type=="blur")
{
style.background="white";
}
}
JavaScript is not necessary for this task, just use css (:focus is supported since IE8)
https://developer.mozilla.org/en-US/docs/CSS/:focus
input { background: lightgray; }
input:focus { background: white; }
Only if this effect is absolutely needed also on < IE8 then JS (properly wrapped in a conditional comment) can be used, but even in this scenario it is recommended to keep off style from logic: e.g.
function ChangeBgColor(obj, evt) {
obj.className = (evt.type === "focus") ? "focus" : "";
}
and use this style
input { background: lightgray; }
input:focus,
input.focus { background: white; }
obj.style.background = "#C8C8C8";
What is style? You have not defined it anywhere in your code above:
function ChangeBgColor(obj, evt)
{
if(evt.type=="focus")
style.background ="lightgrey"; //<--what is style?
else if(evt.type=="blur")
{
style.background="white";
}
}
I am guessing that you wanted something like
obj.style.background ="lightgrey";
And in the code above, simplified
function ChangeBgColor(obj, evt)
{
obj.style.background = (evt.type=="focus") ? "lightgrey" : "white";
}
The best answer is to use pure CSS.
Yep, you should try this javascript code to change the background color for this element:
var obj = document.getElementById("yourId");
obj.onfocus = function() {
obj.style.backgroundColor = 'red';
}
Now you can change whatever color you want
Try doing it with jQuery.
$('#div').on('focus', function() {
$(this).css({background:'blue'});
});

Categories