Utilizing the power of .not() to conceal all divs with the exception of the one that has been clicked on

I am currently working on a project to enlarge images that have thumbnails within divs.

My issue is that when I click on an image with the .thumbnail class, it enlarges as expected but I want all other products to disappear from view. I attempted adding a class with display: none, but because the image being passed to the function is inside the div, it remains visible. So, I tried using opacity instead, but have not been successful so far. Below, I will include the relevant code snippet.

Any assistance on this matter would be highly appreciated. Thank you.

$(document).ready(function() {
  var images = document.querySelectorAll('.thumbnail');


  images.forEach(function(image) {
    image.addEventListener('click', enlarge);
  });

  function enlarge(e) {
    var image = e.target,
      interval,
      height = 200,
      width = 200,
      z = $(this).css("z-index"); //Obtain the current z-index of the image which has been clicked
    /*thisProduct = */

    $(this).css("z-index", z + 10); //increase the z-index of just the image which has been selected by 10
    $('#product-container').addClass('disable-click'); //Stops other products from being enlarged whilst another is
    $('.unhidden').not($(this)).addClass('noOpacity');

  }

});
.noOpacity {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product-container">
  <div class="product-wrapper">
    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/home-bg.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Mexican Nachos - £6.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/enchilada.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Enchiladas - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/quesadilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Quesadilla - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/shrimp.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Shrimp Stir Fry - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tacos.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tacos - £5.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tortilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tortillas - £7.99
      </div>
    </div>
  </div>
</div>
<!-- Product container -->

Answer №1

Event handlers are attached to the .thumbnail elements instead of the .unhidden elements. To target the parent element, use .closest()/.parents(), then you can use not(). Therefore, use

$('.unhidden').not($(this).closest('.unhidden')).addClass('noOpacity');

instead of

$('.unhidden').not($(this)).addClass('noOpacity');

$(document).ready(function() {
  var images = document.querySelectorAll('.thumbnail');


  images.forEach(function(image) {
    image.addEventListener('click', enlarge);
  });

  function enlarge(e) {
    var image = e.target,
      interval,
      height = 200,
      width = 200,
      z = $(this).css("z-index"); //Obtain the current z-index of the image which has been clicked

    $(this).css("z-index", z + 10); //increase the z-index of just the image which has been selected by 10
    $('#product-container').addClass('disable-click'); //Stops other products from being enlarged whilst another is
    $('.unhidden').not($(this).closest('.unhidden')).addClass('noOpacity');

  }

});
.noOpacity {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product-container">
  <div class="product-wrapper">
    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/home-bg.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Mexican Nachos - £6.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/enchilada.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Enchiladas - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/quesadilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Quesadilla - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/shrimp.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Shrimp Stir Fry - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tacos.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tacos - £5.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tortilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tortillas - £7.99
      </div>
    </div>
  </div>
</div>
<!-- Product container -->

Answer №2

Why do you mix jQuery with pure js? Let's accomplish it solely using jQuery.

$(document).ready(function() {
  $('.thumbnail').click(function(e) {
    var image = e.target,
      interval,
      height = 200,
      width = 200,
      z = $(this).css("z-index");
    $(this).css("z-index", z + 10);
    $('#product-container').addClass('disable-click');
    $('.unhidden').not($(this).parent().parent()).addClass('noOpacity');
  });
});
.unhidden {}

.noOpacity {
  opacity: 0;
  transition: .5s ease all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product-container">
  <div class="product-wrapper">
    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/home-bg.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Mexican Nachos - £6.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/enchilada.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Enchiladas - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/quesadilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Quesadilla - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/shrimp.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Shrimp Stir Fry - £10.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tacos.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tacos - £5.99
      </div>
    </div>

    <div id="product" class="unhidden">
      <div class="image-container">
        <img src="assets/tortilla.jpg" class="thumbnail">
      </div>
      <div class="product-text">
        Tortillas - £7.99
      </div>
    </div>
  </div>
</div>
<!-- Product container -->

Answer №3

Utilize classes and IDs in order to create the desired functionality. For instance:

<div class='item'>X</div>
<div class='item'>Y</div>
<div class='item' id='2'>Z</div>

Experiment with this function:

function displayOne(identifier) {
    $('.item').not('#' + identifier).hide();
}

displayOne(2);​

Hopefully, this solution proves beneficial.

Answer №4

Give this a shot:

$('.thumbnail').on('click', function(){
    $('.image-container').not(this).closest('.image-container').toggle();
})

When you click on a thumbnail, all other thumbnails will toggle their visibility (except for the clicked one).

Answer №5

When utilizing .not($(this)), it is important to note that the reference 'this' pertains to the image itself, not the div containing '.unhidden'. Here is an alternative approach:

$(document).ready(function () {
    var pictures = document.querySelectorAll('.thumbnail');

    pictures.forEach(function(pic) {
        pic.addEventListener('click', expand);
    });
});

function expand(e) {
    var picture = e.target,
        interval,
        height = 200,
        width = 200,
        z = $(this).css("z-index"); //Obtain the current z-index of the clicked image
        /*thisProduct = */

    $(this).css("z-index", z + 10);  //Increase the z-index of the selected image by 10
    $('#product-container').addClass('disable-click'); //Prevent other products from enlarging simultaneously
    $('.unhidden').not($(this).closest('.unhidden')).addClass('noOpacity');
    /*$('.unhidden').addClass("hide");*/

}

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

What are some techniques for styling a label element with an empty for attribute using CSS?

Here is what I currently have: <label class="filter-label" for="pv[]181"> ::before white <span class="count">5</span> ::after </label> My goal is to modify the ::after element within that label, but so far my attempts ...

Having trouble figuring out why Ajax is sending Null to my .net core MVC controller

Learning Ajax and jQuery has been quite a challenge for me as a beginner. My current task involves passing an object with two string arrays - one for search parameters, the other for search values. The problem arises when I click the submit button and th ...

"Escaping from the typeahead feature in Angular-UI Bootstrap results in the input field value becoming

Having some difficulty solving a particular edge case scenario. When I select a value from the dropdown of the typeahead using either the keyboard or mouse, the ng-model in the input field is populated correctly. However, if I type a few letters and then ...

Continuously iterate through MySQL results with Ajax every second

I am facing a challenge with my class that retrieves data from a database and loops through the results. The database is updated regularly, but I do not want to refresh the page due to certain reasons. //file class.php class order { function getOrder ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...

jQuery will parse and retrieve new XML data based on the contents of the initial

My jQuery code is functional on this link as it reads an XML file. Now, I want to enhance the functionality so that when a user clicks on News, Articles, Destinations (just as an example), it will read the corresponding XML data. For instance, the News X ...

Issue with accessing the response object and dynamically generated HTML elements beyond the function in Javascript

I am in the process of developing a todo application using Django and Ajax. Upon loading, I retrieve all tasks from the database and display them. When a user clicks on a task, my goal is to mark it as completed. However, I am encountering the following is ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

Utilizing AngularJS Directives: Extract a HTML attribute as a character sequence, employed as a key in a dictionary

My goal is to create an equation tag that utilizes a label attribute to determine which equation to display. Below is the code for my app: (function(){ var app = angular.module('mathDocument', []); app.directive('equation', fu ...

Every time I attempt to insert a background image into a div using jQuery, I am consistently faced with a 404 error message

When I hit enter in my search bar, a new div is created each time. However, I am struggling to assign a background image to the created div as I keep receiving a 404 error in the console. Below is the code snippet I'm working with: function appendToD ...

Is it possible for OrbitControls to maintain rotation based on model origin even while panning?

Let me illustrate my question through an image: Shown here is the top view from the camera, with a grey cube representing a 3D model. The 'X' marks the center of rotation, while the arrow indicates the direction of rotation: Typically, when p ...

Sending messages to a different page: A step-by-step guide

I need to create buttons that, when clicked, will send a specific message or number to another page. For example, clicking button 1 should send "1" and clicking button 2 should send "2". I am looking for a way to achieve this functionality using either j ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

How to automatically redirect to new Django URL after Ajax function successfully runs?

I have implemented an AJAX function to check the validity of user input usernames. This function sends a request to a view which checks the validity and returns a JSON response. The AJAX function I have written makes a call to a specific URL with the user ...

What is the best way to turn an entire table into a clickable link that leads to a different HTML page?

I have created a table that I want to turn into a button linking to another page. The table's values need to be changeable based on data from a database, such as changing the parameter to pH and the value to 7. However, the button should redirect to t ...

What sets apart .ejs from .html files?

In my Node Js project, all front end files are in .ejs format and call the server.js for backend work. 1) Is there additional functionality provided by ejs compared to html? 2) Does this pertain to expressJs functionality in Node? 3) Can I use angularJs ...

Conceal all components on a webpage with the exception of a designated div

I am looking to selectively hide elements on the page, revealing only the contents of div.k1. The page contains numerous elements. How can I achieve this using just CSS? <div>1-this will be hidden</div> <div class="k1"> 2-this div wi ...

ReactJS: The uniqueness of [ this.props ] compared to [ props in this ] is incomprehensible

Inside the componentDidMount method, there is a continuous section of code: console.log('hv props'); for(var i = 0; i<20; i++){ console.log(this); console.log(this.props); } console.log('hv props end'); It is expected that ...