Change Div Class on click - javascript

I'm trying to change Div class on click. What I'm currently trying to do:
I got this on my divs:
onclick"changeClass()"
and this is my function
function changeClass(){
$("#test123").attr("class", "classname");
}
However it's not working. You should now that I generate many divs with Id test123 with foreach loop so that may be the problem but I'm not really sure

You forgot the =:
onclick="changeClass()"
Also, you need to specify which?
onclick="changeClass(this)"
Then in the code:
function changeClass(which) {
$(which).attr("class", "classname");
}
Instead of all these, since you are using jQuery, you can do it in a simple way:
$(function () {
$("div").click(function () {
this.className = "classname";
});
});
.classname {
background: #ccf;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test2">Test 2</div>
<div id="test3">Test 3</div>
<div id="test4">Test 4</div>
If you want multiple classes, it is always better to add and remove class.
$(function () {
$("div").click(function () {
$(this).addClass("classname");
});
});
.classname {
background: #ccf;
}
.myClass {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test2" class="myClass">Test 2</div>
<div id="test3">Test 3</div>
<div id="test4" class="myClass">Test 4</div>
This way, it doesn't affect the previous classes.

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/onclick
onclick
Type: script code
This event handler is called when the object is clicked.
Example
< image src="hello.png" onclick="alert('Hi')"/>
As described on example, it should be written as onclick=foo(args)
changeClass = function(){
document.querySelector("div").setAttribute('class', 'black');
}
.red {
background: red;
}
.black {
background: black;
}
<div class="red" onclick="changeClass()">
lorem
</div>
<br>
<button onclick="changeClass()">click me to change class</button>

Related

How to Toggle Mouse Hover Event on Click?

I want to change the color of element on Hover. However I want to disable hover effect while clicking on the element and set the clicked element red. Again if anyone clicks on the element , and I want to enable the Hover effect and apply the hover effect.
$('.divElement').on('mouseenter', function () {
$(this).addClass('red');
});
$('.divElement').on('mouseleave', function () {
$(this).removeClass('red');
});
$('.divElement').on('click', function () {
$(this).removeClass('red');
$(this).off('mouseenter mouseleave');
});
I Have tried this jQuery Code.
<div class="divElement">Element 1</div>
<div class="divElement">Element 2</div>
<span class="divElement">Element 3</div>
<div class="divElement">Element 4</div>
.divElement {
color: blue;
}
.divElement.red {
color: red;
}
What you have tried is just to disable (unbind) the Hover event. What You actually need is to toggle the hover event if it is clicked.
First of all, I would like to suggest you, to change <span> tag to <div> or add CSS for class .divElemenT{ display:block;} else inline-block element and block element may hover at once.
var hoverEvent= true;
$(".divElement").hover(
function() {
if(hoverEvent) $(this).toggleClass("red");
}
);
$('.divElement').click(function() {
$(this).toggleClass('selected');
$('.divElement').not(this).removeClass('selected,red');// remove this line if you want multiple selector
hoverEvent= !hoverEvent;
});
.divElement {
color: blue;
display:block;
}
.divElement.red {
color: red;
}
.selected{
font-weight:bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divElement">Element 1</div>
<div class="divElement">Element 2</div>
<span class="divElement">Element 3</span>
<div class="divElement">Element 4</div>
Please leave a comment if it doesn't work.
I suggest you create a hover class which indicates that the class is hoverable. Then in your jQuery you can target elements with .hover class for your mouseenter and mouseleave leave events. This means instead of turning off the event listeners for your elements you can instead simply toggle the hover class for each element.
See working example below:
$(document).on('mouseenter', '.divElement.hover', function() {
$(this).addClass('red');
});
$(document).on('mouseleave', '.divElement.hover', function() {
$(this).removeClass('red');
});
$('.divElement').on('click', function() {
$(this).toggleClass('hover');
});
.divElement {
color: blue;
}
.divElement.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divElement hover">Element 1</div>
<div class="divElement hover">Element 2</div>
<div class="divElement hover">Element 3</div>
<div class="divElement hover">Element 4</div>
Note: You need to use $(document).on as you are dynamically changing the classes after the event biding initially occurs, allowing you to listen to events on elements dynamically added/changed.
try this
$('.divElement').click(function(){
if($(this).hasClass("red")||$(this).hasClass("selected")){
$('.divElement').toggleClass("red");
$(this).toggleClass("selected");
}
});
.red:hover,.selected{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divElement red">Element 1</div>
<div class="divElement red">Element 2</div>
<span class="divElement red">Element 3</span>
<div class="divElement red">Element 4</div>
Use mousedown event. Click responds after completing the click, mousedown works in between the click completion.
$('.divElement').on('mouseenter', function () {
$(this).addClass('red');
});
$('.divElement').on('mouseleave', function () {
$(this).removeClass('red');
});
$('.divElement').on('mousedown', function () {
$('.divElement').removeClass('red');
$(this).addClass('red');
$('.divElement').off('mouseenter mouseleave');
});
.divElement {
color: blue;
}
.divElement.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divElement">Element 1</div>
<div class="divElement">Element 2</div>
<span class="divElement">Element 3</span>
<div class="divElement">Element 4</div>
Your approach by toggle class "red" is correct. I just change a bit
HTML
<div class="divElement red">Element 1</div>
<div class="divElement red">Element 2</div>
<div class="divElement red">Element 3</div>
<div class="divElement red">Element 4</div>
CSS
.divElement {
color: blue;
}
.divElement.red:hover, .divElement.selected {
color: red;
}
JQUERY
$('.divElement').on('click', function () {
$(this).toggleClass('red selected');
});
The idea is only make the hover event in class "red", then we toggleClass red for element when clicked.

How to prevent addClass and removeClass repetition

I'm adding active class to the buttons, and also i'm adding list/grid class to the cards-wrapper based on the button clicked.
Below is the working code. is there a way to write less code to achieve the same output?
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').removeClass('active');
$(this).addClass('active');
if ($(this).hasClass('list')) {
$('.cards-wrapper').removeClass('grid').addClass('list');
}
else if($(this).hasClass('grid')) {
$('.cards-wrapper').removeClass('list').addClass('grid');
}
});
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>
You can use the jQuery toggleClass method. As the name suggests, this method toggles the given classes for all the elements in the selection.
You can reduce your if/else logic to just one if statement by checking whether the button that was clicked on is not active. Once you have established that the button is not active, you can then just toggle the classes for both of the buttons and for the content wrapper div.
$('.buttons button').click(function(e) {
e.preventDefault();
if (!$(this).hasClass('active')) {
$('button').toggleClass('active');
$('.cards-wrapper').toggleClass('grid list');
}
});
.active {
color: green;
}
.list {
color: red;
}
.grid {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button>Grid</button>
<button class="active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>
Using the toggleClass method in this way will break if you add more buttons, though, so take care with it.
There's not much you can do there as you are having two action buttons, if you can make it into a single one, then you can use jQuery's .toggleClass() method here. Hence, you don't have to check for classes using .hasClass() every time.
$('.buttons button').click(function(e) {
//some of your code here
$('.cards-wrapper').toggleClass('grid list');
});
Try using ternary operator not toggleClass() because it will cost bug.
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').removeClass('active');
$(this).addClass('active');
$(this).hasClass('list') ? $('.cards-wrapper').removeClass('grid').addClass('list') : '';
$(this).hasClass('grid') ? $('.cards-wrapper').removeClass('list').addClass('grid') : '';
});
.active{
color:green !important;
}
.list{
color:red;
}
.grid{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>
Try with toggleClass() function of jquery
In your answer addClass() and removeClass() .its right.
But better use with toggleClass().because toggle function to check the class name already present or not.if is it present to remove the class name ,is not add the class.
Its handle with one or more function .See the jquery documentation of
toggleClass()
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').toggleClass('active');
if($(this).hasClass('list')){
$('.cards-wrapper').toggleClass('grid list');
}
else if($(this).hasClass('grid')) {
$('.cards-wrapper').toggleClass('list grid');
}
});
.active{
color:green !important;
}
.list{
color:red;
}
.grid{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>

Javascritpt change class to a div near to his grand-father

I want to dynamically change the class of the element #sidePanel from .compact to .expanded, in this code:
<div id="sidePanel" class="compact"></div>
<div id="topbar">
<div id="buttonContainer">
<div id="button"></div>
</div>
</div>
I'm stuck here, I can't apply the class to the correct <div>, I can just add the class to the topbar:
$(document).ready(function(){
$("#button").mouseover(function(){
$("this").parent().eq(2).addClass(".expanded").removeClass(".compact");
});
});
I also tried this:
$(document).ready(function(){
$("#button").mouseover(function(){
$("#sidepanel").addClass(".expanded").removeClass(".compact");
});
});
Your second example was pretty close. When you $.addClass() and $.removeClass(), or are referring to classnames outside of using a selector to target something, just reference the class name (no need for the leading .). Also JS (and CSS) are case-sensitive, so $('#sidepanel') won't target #sidePanel - the cases need to match.
$("#button").mouseover(function() {
$("#sidePanel").addClass("expanded").removeClass("compact");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
<div id="buttonContainer">
<div id="button">button</div>
</div>
</div>
In your first example, $(this) is how you reference this in jQuery. If you put this in quotes, the word this is treated as a string literal instead. And since to use $.parent() you would need to go up 2 levels, you should use $.parents() with the ID of the parent you want to target, then use $.prev() to select the previous element, which is #sidePanel. So to traverse the DOM like that, this is how I would do it.
$("#button").mouseover(function() {
$(this).parents('#topbar').prev().removeClass('compact').addClass('expanded');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
<div id="buttonContainer">
<div id="button">button</div>
</div>
</div>
Your problem is you used $("#sidepanel") instead of $("#sidePanel")
Here's a working example after the change is made:
$(document).ready(function(){
$("#button").on('mouseover', function(){
$("#sidePanel").addClass("expanded").removeClass("compact");
});
});
#topbar > div {
width: 100px;
height: 30px;
background: #ccc;
margin-top: 20px;
}
#sidePanel {
width: 100%;
height: 40px;
background: #ccc;
}
#sidePanel.expanded {
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidePanel" class="compact"></div>
<div id="topbar">
<div id="buttonContainer"></div>
<div id="button"></div>
</div>
first: the solution
$(document).ready(function()
{
$("#button").mouseover(function()
{
// class names - without the dot
$("#sidepanel").addClass("expanded").removeClass("compact");
});
});
then: why you were really close on your first attempt
$(document).ready(function()
{
$("#button").mouseover(function()
{
// $(this) selector uses the `this` keyword (not as a string)
$(this).parent().eq(2).addClass(".expanded").removeClass(".compact");
});
});

Run JS by clicking a div element

Im working on a website that has a few different colored boxes made with divs, and I want to use them to open certain things. Whether it be music, photos, etc. Im using JS to generate a random number and use the number to choose which song to open, but I have no clue how to attach it to the div itself.
</head>
<body style="background-color:#FFF;">
<div id="center">
<div id="header">
<div id="title"><h1>welcom3 :-)</h1></div>
<div id="wrapper">
<div id="redbox">
</div>
<div id="6box">
</div>
<div id="bluebox">
</div>
<div id="greenbox">
</div>
<div id="yellowbox">
</div>
<div id="yellowboxmargin">
</div>
<div id="yellowboxmargin">
</div>
<div id="yellowboxmargin">
</div>
</div>
</div>
</body>
</html>
use jQuery
<div id="box1"></div>
<script>
$(document).ready(function() {
$("#box1").click(function(){
yourfunc();
}
})
</script>
If you need run js code without jquery, use this example.
In head:
<script>
function hello() {
// do something
}
</script>
In body:
<div onclick="hello()">Hello</div>
I would follow the advice of Buddhi Abeyratne and use jQuery. Of course, this is just a guess, but I would say that due to the nature of your project, it will make things easier for you.
jQuery has different methods to attach events to an alement. In this case, you can use the shortcut ".click()".
I leave you here a snippet:
function do_something_cool(box)
{
alert("I have code to make something awesome with " + box.attr("id"));
}
$(document).ready(function()
{
$("#wrapper div").click(function() { do_something_cool($(this)); });
});
body
{
background-color: #FFF;
}
.colored_box
{
height: 50px;
width: 50px;
margin: 5px;
}
#redbox
{
background-color: red;
}
#bluebox
{
background-color: blue;
}
#greenbox
{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="center">
<div id="header">
<div id="title"><h1>welcom3 :-)</h1></div>
<div id="wrapper">
<div id="redbox" class="colored_box"></div>
<div id="bluebox" class="colored_box"></div>
<div id="greenbox" class="colored_box"></div>
</div>
</div>
</div>
</body>
But if you decide to don't use jQuery, here you have the vanilla javascript:
window.onload = function()
{
var boxes = document.getElementById("wrapper").getElementsByTagName("div");
for (var i = 0; i < boxes.length; i++)
{
boxes[i].addEventListener("click", do_something_cool);
}
}
function do_something_cool(evt)
{
alert("I have code to make something awesome with " + evt.target.id);
}
Btw, I guess it is just a copy/paste thing, but you forgot to close one div.
Also, pay attention to how I have separated html, js and css in the snippet. You should avoid inline js and css.
Good luck!

Click event and for loop

HTML code:
<div class="test" id="inner1">
ONE
</div>
<div class="test" id="inner2">
TWO
</div>
<div class="test" id="inner3">
THREE
</div>
<div class="test1" id="outer1">
ONE
</div>
<div class="test1" id="outer2">
TWO
</div>
<div class="test1" id="outer3">
THREE
</div>
Javascript code:
<script type="text/javascript">
for (var i=1;i<=3;i++)
{
$("#inner"+i).click(function () {
$("#outer"+i).css("background-color","blue")
});
}
</script>
and the CSS:
.test{
width: 100px;
padding: 10px;
background-color: green;
margin-bottom:10px;
cursor:pointer;
}
.test1{
width: 100px;
padding: 10px;
background-color: red;
margin-bottom:10px;
}
What I want is to change background color of outer1 by clicking on inner1, change background color of outer2 by clicking on inner2 and change background color of outer3 by clicking on inner3. The above code does not work since it looks for outer4 (i=4) which does not exist when event click is triggered... Do you have any idea how to implement the above with some kind of loop?
Thank you
http://jsfiddle.net/Lpwmyspo/1/
When you iterate like that, the i inside the click function isn't evaluated until you actually click something, and at that time the loop has finished and the value of i is the last thing it was set to in the loop.
The real question is why you're using a loop to begin with when you can use the attribute-starts-with selector and this instead
$('[id^="inner"]').on('click', function () {
$('#outer' + this.id.slice(-1)).css("background-color","blue");
});
FIDDLE
How about?
$(".test").on("click", function() {
var which = this.id.replace(/^inner/, "outer");
$(".test1").css("background-color","transparent"); // in case you need to reset the background
$("#" + which).css("background-color","blue");
});
Demo#Fiddle
Do it in the following way:
<div class="test" id="inner1" onclick="abc(this)">
ONE
</div>
<div class="test" id="inner2" onclick="abc(this)">
TWO
</div>
<div class="test" id="inner3" onclick="abc(this)">
THREE
</div>
<div class="test1" id="outer1">
ONE
</div>
<div class="test1" id="outer2">
TWO
</div>
<div class="test1" id="outer3">
THREE
</div>
and the JavaScript part as follows:
<script type="text/javascript">
function abc(e){
var id = e.id;
var lastchar = id.substr(id.length -1);
document.getElementById("outer"+lastchar).style.backgroundColor='blue';
}
</script>

Categories