Home > Blockchain >  Add active class on Div with JavaScript
Add active class on Div with JavaScript

Time:09-02

I want to make another image change when I click on an image. The change is working. But it doesn't show me which is active for the small "clickimage".

CodePen: https://codepen.io/timbos/pen/vYjBZqz

Please help me with this.

.container{
display:flex; 
  flex-wrap:wrap; 
  gap:30px; 
  justify-content: center; 
  margin-top: 20px;"
}
.img-responsive{
max-width:100%;
}
.activeclick {
filter: grayscale(0%)!important;
}

.clickimage {
filter: grayscale(100%);
cursor:pointer; 
width: 195px; 
height: 61px; 
background-size: contain;
}
<div style="max-width: 1024px;">
    <img  id="Images" src="https://abload.de/img/15iiid.jpg" />
    <div >
        <div  onclick="changeImage('https://abload.de/img/15iiid.jpg')" style=" background-image: url(https://abload.de/img/click1d0f8r.jpg); ">


        </div>

        <div  onclick="changeImage('https://abload.de/img/289ejs.jpg')" style="background-image: url(https://abload.de/img/click2bwddr.jpg);">
        
        </div>

        <div  onclick="changeImage('https://abload.de/img/33dfif.jpg')" style=" background-image: url(https://abload.de/img/click3q0ik5.jpg); 
">
            &nbsp;
        </div>
    </div>
</div>
<script>   
    
    function changeImage(fileName){
     let img = document.querySelector("#Images");
        img.setAttribute("src", fileName);
      
 

  var elems = document.querySelectorAll("activeclick ");
  [].forEach.call(elems, function(el) {
    el.classList.remove("activeclick");
  });
  e.target.className = "activeclick";
}
  
</script>

CodePudding user response:

  1. function "changeImage" has second parameter "this" (added also into HTML onclick for target identification in function)

  2. var elems = document.querySelectorAll(".activeclick"); (there was missing dot for classname)

  3. e.target.className = "activeclick"; was changed to e.classList.add("activeclick"); (better syntax for classname addition)

.container{
display:flex; 
  flex-wrap:wrap; 
  gap:30px; 
  justify-content: center; 
  margin-top: 20px;"
}
.img-responsive{
max-width:100%;
}
.activeclick {
filter: grayscale(0%)!important;
}

.clickimage {
filter: grayscale(100%);
cursor:pointer; 
width: 195px; 
height: 61px; 
background-size: contain;
}
<div style="max-width: 1024px;">
    <img  id="Images" src="https://abload.de/img/15iiid.jpg" />
    <div >
        <div  onclick="changeImage('https://abload.de/img/15iiid.jpg', this)" style=" background-image: url(https://abload.de/img/click1d0f8r.jpg); ">


        </div>

        <div  onclick="changeImage('https://abload.de/img/289ejs.jpg', this)" style="background-image: url(https://abload.de/img/click2bwddr.jpg);">
        
        </div>

        <div  onclick="changeImage('https://abload.de/img/33dfif.jpg', this)" style=" background-image: url(https://abload.de/img/click3q0ik5.jpg); 
">
            &nbsp;
        </div>
    </div>
</div>
<script>   
    
    function changeImage(fileName, e){
     let img = document.querySelector("#Images");
        img.setAttribute("src", fileName);
      
 

  var elems = document.querySelectorAll(".activeclick");
  [].forEach.call(elems, function(el) {
    el.classList.remove("activeclick");
  });
  e.classList.add("activeclick");
}
  
</script>

CodePudding user response:

.container{
display:flex; 
  flex-wrap:wrap; 
  gap:30px; 
  justify-content: center; 
  margin-top: 20px;"
}
.img-responsive{
max-width:100%;
}
.activeclick {
filter: grayscale(0%)!important;
}

.clickimage {
filter: grayscale(100%);
cursor:pointer; 
width: 195px; 
height: 61px; 
background-size: contain;
}
<div style="max-width: 1024px;">
    <img  id="Images" src="https://abload.de/img/15iiid.jpg" />
    <div >
        <div  onclick="changeImage(event,'https://abload.de/img/15iiid.jpg')" style=" background-image: url(https://abload.de/img/click1d0f8r.jpg); ">


        </div>

        <div  onclick="changeImage(event,'https://abload.de/img/289ejs.jpg')" style="background-image: url(https://abload.de/img/click2bwddr.jpg);">
        
        </div>

        <div  onclick="changeImage(event,'https://abload.de/img/33dfif.jpg')" style=" background-image: url(https://abload.de/img/click3q0ik5.jpg); 
">
            &nbsp;
        </div>
    </div>
</div>
<script>   
    
    function changeImage(event,fileName){
     let img = document.querySelector("#Images");
        img.setAttribute("src", fileName);
      
 

  var elems = document.querySelectorAll("activeclick ");
  [].forEach.call(elems, function(el) {
    el.classList.remove("activeclick");
  });
  event.target.classList.add("activeclick");
}
  
</script>

Like this it should work. It is mostly cause e was not defined and you have to pass the event to the function manually. If you use it like this.

But I highly reccommend declaring eventlisteners through js and not defining them in the html.

CodePudding user response:

I've reworked your HTML so that it doesn't use inline onclick attributes. Please don't use them as they are part of an old JS spec; we have many better alternatives, like addEventListener. Even browser vendors advice to use against them - source.

Also using [].forEach.call comes from a time where browser support for the forEach method on a NodeList was shotty. Looping just became easier with for...of.

Every function that is used as a callback for an event - for examle with addEventListener - exposes an Event object. You forgot to expose the parameter which makes it difficult to know which button was pressed.

const img = document.querySelector("#Images");
const buttons = document.querySelectorAll('.clickimage');

for (const button of buttons) {
  button.addEventListener('click', changeImage);
}

function changeImage(event) {
  event.preventDefault();
  
  const fileName = event.target.value;
  img.src = fileName;
  
  for (const button of buttons) {
    button.classList.remove('activeclick');
  }
  
  event.target.classList.add('activeclick');
}
.container {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  justify-content: center;
  margin-top: 20px;
}

.img-responsive {
  max-width: 100%;
}

.activeclick {
  filter: grayscale(0%)!important;
}

.clickimage {
  filter: grayscale(100%);
  cursor: pointer;
  width: 195px;
  height: 61px;
  background-size: contain;
}
<div style="max-width: 1024px;">
  <img  id="Images" src="https://abload.de/img/15iiid.jpg" />
  
  <div >
    <button  value="https://abload.de/img/15iiid.jpg" style=" background-image: url(https://abload.de/img/click1d0f8r.jpg); "></button>

    <button  value="https://abload.de/img/289ejs.jpg" style="background-image: url(https://abload.de/img/click2bwddr.jpg);"></button>

    <button  value="https://abload.de/img/33dfif.jpg" style=" background-image: url(https://abload.de/img/click3q0ik5.jpg); 
"></button>
  </div>
</div>

CodePudding user response:

You have to pass event to function, something like this

<element onclick="changeImage('https://abload.de/img/33dfif.jpg', event)" ...

and in your function, change parameters to this

 function changeImage(fileName, e) {

so you get two parameters, filename and event

CodePudding user response:

The solution with a minimum change of your code

  1. Change var elems = document.querySelectorAll("activeclick"); to var elems = document.querySelectorAll(".activeclick");.
  2. Change e.target.className = "activeclick"; to event.target.classList.add("activeclick");.

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  justify-content: center;
  margin-top: 20px;
}

.img-responsive {
  max-width: 100%;
}

.activeclick {
  filter: grayscale(0%)!important;
}

.clickimage {
  filter: grayscale(100%);
  cursor: pointer;
  width: 195px;
  height: 61px;
  background-size: contain;
}
<div style="max-width: 1024px;">
  <img  id="Images" src="https://abload.de/img/15iiid.jpg" />
  <div >
    <div  onclick="changeImage('https://abload.de/img/15iiid.jpg')" style=" background-image: url(https://abload.de/img/click1d0f8r.jpg); "></div>
    <div  onclick="changeImage('https://abload.de/img/289ejs.jpg')" style="background-image: url(https://abload.de/img/click2bwddr.jpg);"></div>
    <div  onclick="changeImage('https://abload.de/img/33dfif.jpg')" style=" background-image: url(https://abload.de/img/click3q0ik5.jpg); 
">&nbsp;</div>
  </div>
</div>
<script>
  function changeImage(fileName) {
    let img = document.querySelector("#Images");
    img.setAttribute("src", fileName);

    var elems = document.querySelectorAll(".activeclick");
    [].forEach.call(elems, function(el) {
      el.classList.remove("activeclick");
    });
    event.target.classList.add("activeclick");
  }
</script>

CodePudding user response:

  • Instead of html click Event, you should use js events with addEventListener (then you can storage your new image in a data attribute).
  • You should use getElementById instead of querySelector :

getElementById() can run about 15 million operations a second, compared to just 7 million per second for querySelector() in the latest version of Chrome. (Source, Pen I found)

  • Same for getElementsByClassName instead of querySelectorAll.
  • You only have one .activelink so you can select if with querySelector(".activeclick") or getElementsByClassName("activeclick")[0] (I'm not sure wich one is the best).
  • If you use for exemple addEventListener("click", (el) => {}), you can add your class with el.classList.add("activeclick").

I guess it's for the example, but in case you use images as simple as that, you could remake them with css

for (let e of document.getElementsByClassName("button")) {
  e.addEventListener("click", () => {
    document.querySelector(".selected").classList.remove("selected")
    e.classList.add("selected")
  })
}
.container{
  counter-reset: section;
  display:flex; 
  flex-wrap:wrap; 
  gap:30px; 
  justify-content: center; 
  margin-top: 20px;"
}
.button{
  background-color:#bdbdbd;
  cursor:pointer; 
  width: 195px; 
  height: 61px;
  font-weight: bold;
  font-size:20px;

  display: flex;
  justify-content: center;
  align-items: center;
}
.button:before{
  content:"Click\00a0";
}
.button:after{
  counter-increment: section;   
  content: counter(section);
}
.selected{  
  background-color:#A3C2D6;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>

  • Related