Simple javascript click to add class not working - javascript

I am trying to add / remove a class on an element that is clicked liek this
function myFunction() {
this.classList.add("myclass");
}
#first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background: red;
color: white;
}
<div id="first" onclick="myFunction(this)">
Click
<div class="second">
</div>
<div class="third">
</div>
</div>
Why is this not working?

You need to pass reference this into function too like:
function myFunction(el) {
el.classList.add("myclass");
}
#first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background: red!important;
color: white!important;
}
<div id="first" onclick="myFunction(this)">
Click
<div class="second">
</div>
<div class="third">
</div>
</div>
PS. add !important into css

Pass the this to the defined function too and check the existence of the class. Try this.
function myFunction(el) {
if(!el.classList.contains("myclass")) {
el.classList.add("myclass");
console.log("added");
} else {
el.classList.remove("myclass");
console.log("removed");
}
}
#first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background: red;
color: white;
}
<div id="first" onclick="myFunction(this)">
Click
<div class="second">
</div>
<div class="third">
</div>
</div>

It doesn't work because this for inline handlers works differently. You can use .call, and that works... but that's still not good.
function myFunction() {
this.classList.add("myclass");
}
#first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background: red !important;
color: white;
}
<div id="first" onclick="myFunction.call(this)">
Click
<div class="second">
</div>
<div class="third">
</div>
</div>
You should avoid inline script altogether and also avoid id selectors in CSS.
Change your id selector to a class selector and change your inline handler to an event listener.
Also, stray strings like "content" are a real pain as your project grows in size. Wrap them in a <span>
const myButton = document.querySelector(".first");
myButton.addEventListener("click", ({
target
}) => target.classList.add("myclass"))
.first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background: red;
color: white;
}
<div class="first">
<span>Click</span>
<div class="second"></div>
<div class="third"></div>
</div>

You are facing 2 issues :
you pass this as a parameter to the onclick event, but don't get it in the function definition (), so you can fix it like below ;
id selector is more specific than class selector, so it always take precedence. You can use a class instead of an id for first div, and then your css rule works :)
function myFunction(el) {
el.classList.add("myclass");
}
.first {
height: 100px;
width: 100px;
background: yellow;
color: black;
}
.myclass {
background-color: red;
color: white;
}
<div class="first" onclick="myFunction(this);">
Click
<div class="second">
</div>
<div class="third">
</div>
</div>

Related

How to use each function jQuery to addClass on it's parent element

just asking can you please tell me how can I achieve it when I clicked the button it should only add the class on its parent div. Currently its adding both the parent div even I click the first button
$( ".main-btn" ).each(function(index) {
$(this).on("click", function(){
$(".main").addClass("addClass")
});
});
.main {
background: yellow;
margin-bottom: 3px;
height: 50px;
}
.main.addClass {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="main-btn">Button</div>
</div>
<div class="main">
<div class="main-btn">Button</div>
</div>
There's no need for .each() here, you can just reference the parent from the clicked element via .closest()...
$(".main-btn").on("click", function() {
$(this).closest(".main").addClass("addClass");
});
.main {
background: yellow;
margin-bottom: 3px;
height: 50px;
}
.main.addClass {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="main">
<div class="main-btn">Button</div>
</div>
<div class="main">
<div class="main-btn">Button</div>
</div>
Also, you might not need jQuery
document.querySelectorAll(".main .main-btn").forEach((btn) => {
btn.addEventListener("click", (e) => {
e.target.closest(".main").classList.add("addClass");
});
});
You can use the parent() method:
$(".main-btn").on("click", function() {
$(this).parent().addClass("addClass");
});
.main {
background: yellow;
margin-bottom: 3px;
height: 50px;
}
.main.addClass {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="main-btn">Button</div>
</div>
<div class="main">
<div class="main-btn">Button</div>
</div>

Toggle appending element to different divs

Is it possible to move .item from .region1 to .region2 when the anchor tag is clicked, and also move it back to .region1 when it is clicked again? So pretty much the behavior of a toggle ?
<a href="#" class="btn">Click</div>
<div class="region1">
<div class="item"></div>
</div>
<div class="region2"></div>
make use of append() to achieve the toggle effect:
function toggleItem(){
var $item = $('.region1').find('.item');
if($item.length !== 0){
$('.region2').append($item);
} else {
$item = $('.region2').find('.item');
$('.region1').append($item);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="btn" onclick='toggleItem()'>Click</a>
<div class="region1">Inside region 1
<div class="item">item</div>
</div>
<div class="region2">Inside region 2</div>
Just build the toggle like function by yourself. Check if the element is is there then use appendTo to move the element.
$('a.btn').click(function() {
if ($('.region1 > .item').length) {
$('.region1 > .item').appendTo('.region2');
}
else {
$('.region2 > .item').appendTo('.region1');
}
});
.region1 { width: 50px; height: 50px; background: red; }
.region2 { width: 50px; height: 50px; background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click
<div class="region1">
<div class="item">item</div>
</div>
<div class="region2"></div>
If there is only one .item in the whole page, you could make it shorter:
$('a.btn').click(function() {
$('.item').appendTo($('.region1 > .item').length ? '.region2' : '.region1');
});
.region1 { width: 50px; height: 50px; background: red; }
.region2 { width: 50px; height: 50px; background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click
<div class="region1">
<div class="item">item</div>
</div>
<div class="region2"></div>
Or without jQuery:
document.querySelector('a.btn').addEventListener('click', function() {
if (item = document.querySelector('.region1 > .item')) {
document.querySelector('.region2').append(item);
} else if (item = document.querySelector('.region2 > .item')) {
document.querySelector('.region1').append(item);
}
});
.region1 { width: 50px; height: 50px; background: red; }
.region2 { width: 50px; height: 50px; background: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click
<div class="region1">
<div class="item">item</div>
</div>
<div class="region2"></div>
Here's a solution in vanilla JavaScript:
var item = document.querySelector('.item');
var region1 = document.querySelector('.region1');
var region2 = document.querySelector('.region2');
document.querySelector('a').addEventListener('click', function() {
if (region1.contains(item)) {
region2.appendChild(item);
} else if (region2.contains(item)) {
region1.appendChild(item);
}
});
.region1 {
width: 100px;
height: 100px;
background-color: aqua;
}
.region2 {
width: 100px;
height: 100px;
background-color: yellow;
}
Click
<div class="region1">
<div class="item">Test</div>
</div>
<div class="region2"></div>
Note:
Because there's probably more than just one single a tag in your page, you should not use ...querySelector('a')... like this. To ensure the proper a tag gets selected, you should make it unique, e. g. by adding an id to it. If you decide to use the way with the id, replace the your querySelector('a') with querySelector('#yourid').
And thank you to eisbehr for helping me to cut down the script in an very effective way.

Change background image of one element to the same image of the other element on click

I'm currently working on a nail polish website and am very new to Jquery. I need to implement a "try it on" page where people can select a colour they like and the nails of the image change to that specific colour.
Basically like this: http://chinaglaze.com/Try-On/index.html
I've tried pulling the html, scripts etc from this link to try figure out how it's been done. However, I have absolutely no idea how to implement this and get it working on my site.
I've been doing a a lot of research and cannot find the answer.
Okay so the hand is a div with a .png background image implemented via css (the nails are transparent). The buttons next to the hand are plain images. Basically when someone selects the specific button image, it must then pull to the div as a background image and repeat. Thus showing through as the nail colour.
I'm not sure if this makes any sense?
Here is a sample snippet for how to set colour of one item on another on click.
(Since you have not provided any HTML i have used a sample mark up)
In the link you have provided they might be using image instead.
$(".item").click(function() {
$("#change").css("background",$(this).css("background"));
});
#change {
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
.item {
height: 100px;
width: 100px;
display: inline block;
float: left
}
#green {
background: green;
}
#red {
background: red;
}
#blue {
background: blue;
}
#yellow {
background: yellow
}
#black {
background: black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="change">
Select a color
</div>
<div class="item" id="green">
</div>
<div class="item" id="red">
</div>
<div class="item" id="blue">
</div>
<div class="item" id="yellow">
</div>
<div class="item" id="black">
</div>
Here is the solution, used the code from above answer and created a working [JSFiddle][1] with few changes
$(".item").click(function() {
$(".screen").css("background",$(this).css("background"));
});
.screen {
border: 1px solid #ccc;
}
#change
{
background:url("http://chinaglaze.com/images/tryon/hand_1.png") 0px 0px no-repeat;
width: 300px;
height: 516px;
}
.item {
height: 100px;
width: 100px;
display: inline block;
float: left;
}
#green {
background: green;
}
#red {
background: red;
}
#blue {
background: blue;
}
#yellow {
background: yellow
}
#black {
background: black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="screen">
<div id="change">
Select a color
</div>
</div>
<div class="item" id="green">
</div>
<div class="item" id="red">
</div>
<div class="item" id="blue">
</div>
<div class="item" id="yellow">
</div>
<div class="item" id="black">
</div>

New to javascript trying to figure this out

So I'm trying to make multiple lights activate on button clicks and I'm not sure what I'm doing wrong here.
I thought I could make this into a function and then pass it the id name but it looks like it's not acting the way I want.
html
<div class="lights">
<div id="red"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<div class="button">
<button id="red_button"> Red Button </button>
<button id="yellow_button">Yellow Button </button>
<button id="green_button">Green Button </button>
</div>
css
.lights{
height: 600px;
width: 200px;
background-color: black;
padding-top: 15px;
}
.button{
padding-top: 20px;
}
#red,
#yellow,
#green {
margin: 0 auto;
background-color: black;
border-radius: 50%;
width: 180px;
height: 180px;
margin-top: 10px;
}
#red.active {
background-color: red;
}
#yellow.active {
background-color: yellow;
}
#green.active {
background-color: green;
}
jquery
function click(e) {
$('#red,#yellow,#green').removeClass('active');
$('e').addClass('active');
}
$('#red_button').click(click('#red'));
$('#yellow_button').click(click('#yellow'));
$('#green_button').click(click('#green'));
http://jsfiddle.net/0m9wos1r/1/
A few things. I wouldn't recommend naming your function after an event, although it should still work. The issue with your code is that you're immediately calling the function, and in the function you quoted the parameter. Use this instead:
function click(e) {
$('#red,#yellow,#green').removeClass('active');
$(e).addClass('active');
}
$('#red_button').click(function () {
click('#red')
});
$('#yellow_button').click(function () {
click('#yellow')
});
$('#green_button').click(function () {
click('#green')
});
.lights {
height: 600px;
width: 200px;
background-color: black;
padding-top: 15px;
}
.button {
padding-top: 20px;
}
#red, #yellow, #green {
margin: 0 auto;
background-color: black;
border-radius: 50%;
width: 180px;
height: 180px;
margin-top: 10px;
}
#red.active {
background-color: red;
}
#yellow.active {
background-color: yellow;
}
#green.active {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lights">
<div id="red"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
<div class="button">
<button id="red_button">Red Button</button>
<button id="yellow_button">Yellow Button</button>
<button id="green_button">Green Button</button>
</div>
Fixed: http://jsfiddle.net/0m9wos1r/4/
2 issues you need to fix:
The function call within the click call. Like so, using an anonymous function:
$('#red_button').click(function(){click('#red')});
The selector within the click function. Like so:
$(e).addClass('active');

Resize divs related to parent divs with jQuery

So I have 4 divs. I want to change the size of the inner divs compared to parent divs.
I want to dynamically change the child div size related to parent's one.
Now I've added .top class, but I don't really know if its needed or if it will be useful.
Here is the fiddle I'm testing with
http://jsfiddle.net/y3597/171/
jQuery below
$(".top").each(function () {
$('.object').width($(".inner").parent().width());
});
CSS below:
.container1 { width: 200px; background: red; padding: 2px; }
.container2 { width: 225px; background: purple; padding: 2px; }
.container3 { width: 250px; background: blue; padding: 2px; }
.container4 { width: 275px; background: black; padding: 2px; }
/* top ? */
.inner { width: 150px; background: gray; }
.object { width: 100px; background: green; }
HTML below:
<div class="container1 top">
<div class="inner">
<div class="object">Text 1</div>
</div>
<div class="container2 top">
<div class="inner">
<div class="object">Text 2</div>
</div>
<div class="container3 top">
<div class="inner">
<div class="object">Text 3</div>
</div>
<div class="container4 top">
<div class="inner">
<div class="object">Text 4</div>
</div>
I think that you are trying to achieve this:
$(".top").each(function () {
$(this).find(".object").width($(this).width());
});
In your code jQuery will check for every element with .object class in DOM on each loop. When you use (this) you are refering to element that is currently "selected" in loop.
Better way to achive this is to set widths od children to 100%, so they will inherit the witdhs from parents.

Categories