4ukh
4ukh

Reputation: 47

with javascript onclick add classname to a div

I want to achieve with javascript something like when i clink on any of thumbnail (btn-1, btn-2 and btn-3) the specific class should be add to box div dynamically.

my code: JSFiddle

document.getElementById('btn-1').onclick = function() {
  document.getElementById('box').className = 'bg-1';
}
#box {
  background-color: darkgray;
  width: 200px;
  height: 200px;
}

.thumbnail {
  width: 30px;
  height: 30px;
  border: 1px solid;
  margin: 5px;
  position: relative;
  float: left;
}

#btn-1 {
  background-color: red;
}

#btn-2 {
  background-color: green;
}

#btn-3 {
  background-color: blue;
}

.bg-1 {
  background-color: red;
}

.bg-2 {
  background-color: blue;
}

.bg-3 {
   background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>

<div class="thumbnail" id="btn-1"></div>
<div class="thumbnail" id="btn-2"></div>
<div class="thumbnail" id="btn-3"></div>

Upvotes: 1

Views: 2867

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

Instead of bothering with classes, use simply a data- attribute like: data-bg="#f00"

$('[data-bg]').css('background', function () {
  $(this).on('click', () => $('#box').css('background', this.dataset.bg));
  return this.dataset.bg;
});
#box {
  background: darkgray;
  width: 120px; height: 120px;
}

[data-bg] {
  width: 30px; height: 30px;
  margin: 5px;
  float: left;
}
<div id="box"></div>
<div data-bg="red"></div>
<div data-bg="#00f"></div>
<div data-bg="rgb(255,0,180)"></div>
<div data-bg="linear-gradient(to right, #E100FF, #7F00FF)"></div>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

Upvotes: 0

Michael Horn
Michael Horn

Reputation: 4089

You can get all the thumbnails as an array, and then iterate through the array and dynamically add an event listener to each, which will add the desired className to box when clicked:

var thumbnails = document.getElementsByClassName('thumbnail');

Array.from(thumbnails).forEach(function(thumbnail) {
    var id = thumbnail.id;
    thumbnail.addEventListener('click', function() {
        document.getElementById('box').className = id.replace('btn', 'bg')
    });
});

Upvotes: 0

TripWire
TripWire

Reputation: 552

You javascript is working, but your CSS isn't.

You need to add !important as follows to .bg-1, .bg-2 and .bg-3

.bg-1 {
  background-color: red !important;
}

Otherwise the id styling is taking preference over the class styling

You can see the classname is being added if you right click on the grey div and choose inspect element in Chrome.

Upvotes: 1

Leo Van Deuren
Leo Van Deuren

Reputation: 435

You want to use jquery .addClass() function:

$('.myButton').addClass('myNewClass');

The function would probably look something like this:

$(function () {
     $('.thumbnail').click(function() {
         $('#box').addClass($(this).attr('id'));
     });
})

Upvotes: 0

Related Questions