One-click process succeeds where two clicks fail

The code below is intended to go through a two-click process as follows:

  1. First click on .imagenes decreases opacity and makes .logo visible.

  2. Second click on .imagenes returns the opacity to 1 and hides .logo again.

However, during this cycle of two clicks, .logo does not show up. Can you identify the reason why?

const imagenes = document.querySelectorAll('.imagenes');
const logos = document.querySelectorAll('.logo');

imagenes.forEach((imagen, index) => {
  let count = 0;
  imagen.addEventListener('click', () => {
    if (count % 2 == 0) {
      imagen.style.opacity = 0.1;
      logos[index].style.opacity = 1;
    } else {
      imagen.style.opacity = 1;
      logos[index].style.opacity = 0;
    }
    count++;
  });
});
   

 html {
      box-sizing: border-box;
      font-size: 16px;
    }
    
    body {
      max-width: 1500px;
      margin: 0 auto;
    }

    .gridA {
      display: grid;
      width: 50%;
      height: auto;
      grid-gap: .5rem;
      grid-auto-rows: minmax(auto, min-content);
      grid-template-columns: 1fr;
      margin-right: .25rem;
      overflow: hidden;
    }

    .gridB {
      display: grid;
      width: 50%;
      height: auto;
      grid-gap: .5rem;
      grid-auto-rows: minmax(auto, min-content);
      grid-template-columns: 1fr;
      margin-left: .25rem;
      overflow: hidden;
    }

    img {
        width: 100%;
        height: auto; /*img use its full width leaving empty height space*/
        object-fit: cover;
        display: block; /*fill empty space remaining after adding img*/
        max-height: 100%;
        overflow: hidden;
    }
    
    #A, #B {
      position: relative;
    }

    .logo {
      position: absolute;
      visibility: hidden;
      top:0;
    }

    .youtube-link {
        position: absolute;
        top: 80%;
        left: 39%;
        width: 15%;
        
    }
    
    .video-link {
        position: absolute;
        top:100%;
        width: 10%;
        left: 44%;
    }
    
    .youtube-link2 {
        position: absolute;
        top: 75%;
        left: 42%;
        width: 15%;
    } 
    
    .youtube-link2:hover {
        opacity: .6;
    }
    
    .video-link:hover {
        opacity: .6;
    } 
    
    .youtube-link:hover {
        opacity: .6;
    }
<<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8>"
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="gridA">

<div id ="A" class="box">
  
  <div class="imagenes">
    <img src="spotify-still.jpg">
  </div>
  
  <div class="logo">
    <img id="Alog" src="Spotify Logo (PNG720p) - Vector69Com.png">
      <a>
        <a class="youtube-link2" target="_blank" href="https://www.youtube.com/watch?v=7ob_q2HsHWM">
          <img id="youspot" src="pngwing.com(1) copy.png" class="youtube-btn">
        </a>
      </a>
  </div>;
</div>;

<div ID ="B" class="box">
  
  <div class="imagenes">
    <img src="audi-q3-1-by-marc-trautmann 2.jpg">
  </div>
  
  <div class="logo">
    <img id="Blog" src="Audi_logo_PNG3.png">>
  </div>
</div>

</div>;

<div class="gridB">
</div><brt

</div><brt

<script src="JS.js"></script>
</body>
</html><brt

Answer №1

When you click just once, the opacity changes in one direction only, requiring a second click to revert it back.

To simplify this process, we can introduce two CSS classes: hide and show, each having an opacity value of 0 or 1.

We can then iterate over all the elements with the class name box:

[ ...document.querySelectorAll('.box') ].forEach(box => {

Within each box, extract the images and logos:

let boxImages = box.querySelector('.images');
let boxLogo = box.querySelector('.logo');

Add an event listener that toggles between the show and hide classes when the images are clicked:

boxImages.addEventListener("click", () => {
        boxLogo.classList.replace('hide', 'show');
        boxImages.classList.replace('show', 'hide');
    });    

Similarly, add another event listener for the logo element to reverse the actions triggered by the first click.


Note: The original link has been removed and placeholder images have been added for demonstration purposes.

[ ...document.querySelectorAll('.box') ].forEach(box => {

    let boxImages = box.querySelector('.images');
    let boxLogo = box.querySelector('.logo');
    
    boxImages.addEventListener("click", () => {
        boxLogo.classList.replace('hide', 'show');
        boxImages.classList.replace('show', 'hide');
    });    
    
    boxLogo.addEventListener("click", () => {
        boxLogo.classList.replace('show', 'hide');
        boxImages.classList.replace('hide', 'show');
    });    
});
#A {
  position: relative;
  border: 1px solid red;
}

.logo {
    position: absolute;
    top:0;
}

.show { opacity: 1; }
.hide { opacity: 0; }
<div id ="A" class="box">
    <div class="images show">
        <img src="https://picsum.photos/50?random=1">
    </div>
    <div class="logo hide">
        <img id="Alog" src="https://picsum.photos/50?random=2">
        <img id="youspot" src="https://picsum.photos/50?random=3" class="youtube-btn">
    </div>
</div>

Answer №2

When it comes to logos, unlike images, you are incorporating graphics that contain spaces in their names.

To address this issue, you have the option to eliminate the spaces or utilize special characters such as a plus (+) sign or %20 to represent space within the file names.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Ajax to send IP addresses and obtain location data

Is there a website or webpage that can be used to input a user's IP address and receive their country or location as plain text? Below is a code snippet demonstrating how I attempted to retrieve the user's IP address: I inserted the following c ...

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

What are effective methods for testing HTML5 websites?

I'm currently working on a project to create a dynamic website using HTML5. The first page will prompt the user for specific inputs, and the following page will adjust accordingly based on these inputs. My main concern now is how to effectively test ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

Preventing Body Overflow Without Affecting Iframe Overflow in Meteor.js

Currently, I am working on a project using Meteor for a Point of Sale (POS) system. For those unfamiliar with it, Meteor is a framework that allows for the use of JavaScript, jQuery, and various other web app scripting languages. The goal of this applicati ...

Use jQuery to populate a span element with information that is solely obtainable within a foreach loop during the rendering of buttons

I am currently navigating through learning MVC, and I have hit a roadblock. Working with Web Forms was more familiar to me, so I find myself struggling quite a bit with this new framework. After dedicating most of my day to it, I realize I need some assist ...

Tips for assessing JSON response data from an AJAX form

I am struggling with how to properly structure a question, but I would like to explain my situation. I am using AJAX to send data and receiving JSON in return. Each value in the JSON response represents a status, and I need to test and react based on these ...

What is the best way to automatically place the cursor in a text box when a webpage is loaded using JavaScript?

Just starting out in web development and looking to enhance my skills. I am trying to find a way to automatically place the cursor in a specific text box on a website when the page loads. Currently, I am experimenting with the Greasemonkey add-on for this ...

What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh. I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far. Check out my code below: v ...

Understanding ReactJs component syntax: Exploring the nuances and distinctions

Currently diving into the world of Reactjs and working on creating a basic component. I'm puzzled about why this particular syntax for a component: import React, { Component } from 'react'; export default class AboutPage extends Component { ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

When the children within a CSS container are floated, set the height of the container to

I've established a simple layout <div class="container"> <div class="sidebar"> </div> <div class="content"> </div> <div style="clear:both;"></div> </div> where .sidebar and .content ...

NextJS compilation sometimes results in undefined errors when using Sass styles

My peace lies in the sass code: .link display: inline-table text-align: center align-self: center margin: 5px 15px font-size: 20px color: black text-decoration: none transition: 0.1s ease-in-out .link:hover text-decoration: underline .l ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

What is the best way to trigger a function exclusively upon clicking a particular element?

My goal is to enable the user to interact with the model by positioning cubes in space upon clicking the "Cubes Mode" button. I currently have a script from the three.js website that achieves this, but I want it to only run when the mentioned button is cli ...

What techniques can I use to generate a 3D visual effect by shifting the background image layer as the user scrolls (creating a Parallax effect

I have combined two images in the heading; one on top of the other. My goal is to create a subtle vertical movement in the background image as the user scrolls, giving the illusion of depth. Both images share the same width, but the background image is tal ...

Blueprint adjusts the height of the menu

After rendering the following code, the menu appears as a table with the ID topMainMenu and a height of 51. However, upon removing the Blueprint stylesheet, the height of topMainMenu reduces to 20, which I believe is the minimum height. <head runat="se ...

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...