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

Retrieving data from a script within a React component

How can I access a variable from a script inside a React component? I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs. <script type="text/javascript">window.deviceType = <%- deviceT ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Modifying an object's label based on a particular value using JavaScript

In my current project involving React.js charts, I am looking to organize data by month. In Django, I have set up a view to display JSON containing the total events per month in the following format: [ { "month": "2022-06-01T00:00:0 ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

Swap out periods with commas in the content of Json Data

I have a JSON file containing percentage data that I am extracting and displaying on my website: <?php $resultData = file_get_contents('https://example.com/json/stats?_l=en'); $jsonData = json_decode($resultData, true); if( isset( ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

Guide on seamlessly adding NPM "dependencies" to index.html using <script> tags in a VUE JS WEBPACK project

Are there any tools available that automatically inject or include NPM dependencies into the index.html file, similar to the GRUNT-BOWER plugin for BOWER dependencies? The project in question is a VUE-CLI WEBPACK project. Can this functionality be achieve ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

What is the best way to save longitude and latitude coordinates in a database using the <input> method?

Learn how to use HTML code <html> <body> <p>Press the button below to receive your coordinates.</p> <button onclick="getLocation()">Get Coordinates</button> <p id="demo"></p> <script> var x = doc ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Updating lists using PHP and Ajax: a dynamic approach

I am currently using a chat service that relies on polling every 20 seconds for new user data in the chat room. I am looking to improve this process by only downloading information for new users who have just joined, rather than re-downloading old data f ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...

What is the CSS method for determining the distance from the top of a container to the edge of the window?

I am working on a basic HTML layout that contains a few elements, including a scrollable div container located below them. Since the height of unknown-height is uncertain due to dynamic element generation, I need a simple method to enable scrolling in the ...

Require this form to be centered flawlessly

<form class="form-horizontal" role="form" id="contactf" action="http://titan.csit.rmit.edu.au/~e54061/wp/form-tester.php" method="post"> <div class="form-group"> <label class="control-label col-sm-2 lb" for="email">Email : </ ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...