The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario:

https://jsfiddle.net/0g1Lvk2j/20/

If you scroll to the end and close the last box by clicking on the orange box, the orange borders of the closed box should transfer to another visible box by removing the class photo-src-as-main from the closed box and adding it to the first visible box. However, this functionality is not working as expected!

<div class="photo fn-photo-upload grid-25 tablet-grid-50 mobile-grid-100" >
  <div class="photo-frame">
    <div class="photo-src fn-photo-upload-src">
      <div class="pu-btn-container"><span class="text-charcoal">/upload</span></div>
    </div>
  </div>
</div>

HTML:

<div class="photo fn-photo-upload grid-25 tablet-grid-50 mobile-grid-100" >
  <div class="photo-frame">
    <div class="photo-src fn-photo-upload-src">
      <div class="pu-btn-container"><span class="text-charcoal">/upload</span></div>
    </div>
  </div>
</div>

CSS

.display-none{
  display:none;
}
.photo-src-control{
    width: 40px;
    height: 40px;
    background-color: orange;
    cursor: pointer;
}
/* Additional CSS properties here */

Javascript/jQuery

$(document).ready(function(){
  $(".photo-src-remove").click(function(){
    var photo=$(this).parents().eq(3);
    var photoFrame=$(this).parents().eq(2);
    photo.addClass("display-none");

    if (photoFrame.hasClass("photo-src-as-main")) {
      // Add and remove classname logic
      $(".photo").not(".fn-photo-upload,.display-none").find(".photo-frame").eq(0).addClass("photo-src-as-main")
      photoFrame.removeClass("photo-src-as-main");
    }
  })

  $(".photo-src").not(".fn-photo-upload-src").click(function(){
    $(".photo-frame").removeClass("photo-src-as-main")
    $(this).parent().addClass("photo-src-as-main")
  })
})

Answer №1

When you click on the orange square element "photo-src-remove," both of your "click" handlers are triggered. This is because its parent is a "photo-src" element, causing the click to bubble up. As a result, the code adds "photo-src-as-main" as intended, but then promptly removes it due to the other click handler.

To resolve this issue, you can prevent event bubbling by adding the following line:

  $(".photo-src-remove").click(function(e){
    e.stopPropagation();                   // <=== stop bubbling
    var photo=$(this).parents().eq(3);
    var photoFrame=$(this).parents().eq(2);
    photo.addClass("display-none");

    if (photoFrame.hasClass("photo-src-as-main")) {
      //I dont understand why it refuses to add and remove this classname
      $(".photo").not(".fn-photo-upload,.display-none").find(".photo-frame:first").addClass("photo-src-as-main")
      photoFrame.removeClass("photo-src-as-main");
    }
  })

Instead of navigating through the DOM structure using .parents(), I recommend utilizing .closest() to explicitly target the parent based on its class name. Relying on DOM hierarchy for navigation can be precarious.

Answer №2

You might want to consider a different approach as the current one seems to be causing some issues. Although it may not look pretty, the key issue here is not with the add/remove class functionality but rather with the element being returned during the selection process.

 $(".photo-src").not(".fn-photo-upload-src").click(function(){
    $(".photo-frame").removeClass("photo-src-as-main")
    var frameList = $(".photo-frame").filter(':visible');
    $(frameList[frameList.length - 1]).addClass("photo-src-as-main")
  })

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

There is a slight misalignment when trying to horizontally center a character within a div

I've experimented with various methods like using a px width or em widths. I've attempted nesting a span and trying different styles such as text-align:center or margin:0 auto. I can manage to center either the R or the S, but struggling to get ...

Node and Angular Error: The specified file or directory does not exist

I have been using the tutorial from scotch.io to build my first node and angular application. I encountered a common issue with relative paths online resulting in the error message Error: ENOENT: no such file or directory. However, after following the tuto ...

Having trouble with blueprintjs icons not appearing as they should on certain pages

I have recently updated an older React application from blueprintjs version 1 to version 4 by following the documentation. However, I am now facing an issue where the icons are not displaying correctly as shown in the image below. Could someone please poi ...

What is the process for sending an email to a designated recipient through an HTML form and then storing it as a record in an HTML table?

<!-- Placeorder part --> <div data-ng-show = "isPlaceOrder"> <div class = "col-lg-10" style = "margin-top:80px"> <div class="panel panel-primary"> <div class = "panel-heading">Drug Request Mail Sender</div&g ...

Creating an NPM Module: Importing your own package as a dependency

Currently, I am in the process of developing a new NPM package. The repository includes an examples directory containing some JavaScript code that is compiled and served locally (or potentially through github.io). The configuration is reminiscent of the s ...

Create a circle at the point where two table cells intersect in an HTML document

How can I create a circular shape at the intersections of HTML tables? I am struggling to figure out a way to incorporate shapes into HTML tables. My goal is to achieve a design similar to the image shown below. I have attempted using text and spans, as we ...

What sets apart Import { module } from lib and import module from lib/module in JavaScript?

I'm currently working on optimizing my vendor bundle.js file, which has gotten quite large due to my use of the material-ui library. import Card from 'material-ui'; // This is not ideal as it imports everything Could someone please explai ...

I am struggling to create a modal component for a settings button

I am currently working with Quasar VueJS and I have a requirement to add a button on my navbar that will trigger a pop-up dialog settings panel. This settings panel will be used for various functionalities such as dynamic theming, although that is somewhat ...

Close button for Chrome application

I am currently venturing into creating a Chrome app for the first time and I am faced with the challenge of implementing a close button using the following HTML code: <html> <head> <link rel="stylesheet" type="text/css" href="as ...

The functionality of the document download button using Express.js and node.js appears to be malfunctioning

For my current project, I am aiming to enable users to effortlessly download a document by simply clicking on a designated button. Project Outline: public/client.js console.log('Client-side code running'); const button = document.get ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

What is the best way to conceal a new HTML5 element in Internet Explorer 8?

Here is an example of the code I'm working with: <div id="body-no-aside"> <div id="content"> Some contents </div> <aside id="aside"> Something aside </aside> </div> I have added html5shiv.js to ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

Creating a Dynamic Cascading Dropdown Menu in ASP.Net MVC2

Currently working with mvc2 and c# ASP.Net, I am attempting to incorporate cascading dropdown lists. The first dropdown is labeled as "group" and the second one as "division". When selecting a group, its respective divisions should be displayed in the seco ...

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

Adjusting the text color for select values within a <td> element

I have a table that is populated with data retrieved from an API. Each cell in the table contains multiple pieces of data. Below is the code used to create the table: <td class="myclass"> <?php $myvar = explode(" ", $json["data"]); ...

Breaking down a JSON Object in Angular 4: Step-by-step Guide

I am working on integrating a JSON API with an Angular 4 frontend, and my goal is to display the data from this JSON Object. Here is the code I have used: <div *ngFor="let Questionnaire of struc.data"> <span>{{Questionnaire.attributes.con ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...