Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues.

I'm hoping for my JavaScript to target only the selected element, not all of them. Check out a demo here.

HTML

<div class="mainPageDiv">
    <div class="dashBoardContainer">
        <div class="dbContainer1 column">
            <div class="flip">
                <div class=" card">
                    <div class="face front">
                        <div class=" portlet   ">
                            <div class="portlet-header"> <span class="red text-uppercase"> edit button works</span>

                                <div class="dropdown pull-right "> <span class="pull-right ">
                            <span class=""  id="edit-changes"><a href="#" > Edit <span class="glyphicon glyphicon-pencil pull-right flipLink" > </span> 
                                    </a>
                                    </span>
                                    </span>
                                    <hr class="hrflipForm">
                                </div>
                                <!-- portlet-content -->
                            </div>
                            <div class="portlet-content lastViewedArticle ">
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text</div>
                            <!-- portlet-header -->
                        </div>
                        <!-- portlet- -->
                    </div>
                    <!-- moveOnchange-->
                    <div class="face back">
                        <div class="inner">
                            <div class="portlet">
                                <div class="flipForm">
                                    <ul class="list-inline pull-right ">
                                        <li class="flipControl" id="save-changes"> <span class="pull-right glyphicon glyphicon-floppy-disk gi-1x opacity7 "></span>

                                        </li>
                                   </ul>
                                </div>
                                <!-- Header Closed -->
                                <div class="portlet-content lastViewedArticle ">
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text</div>
                                <!--- Portlet content -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- dbContainer1 -->
        </div>
        <div class="dbContainer2 column">
            <div class="flip">
                <div class=" card">
                    <div class="face front'>
                        <div class=" portlet   ">
                            <div class="portlet-header"> <span class="red text-uppercase">  edit button doesn't works</span>

                                <div class="dropdown pull-right "> <span class="pull-right ">
                            <span class=""  id="edit-changes"><a href="#" > Edit <span class="glyphicon glyphicon-pencil pull-right flipLink" > </span> 
                                    </a>
                                    </span>
                                    </span>
                                </div>
                                <!-- portlet-content -->
                            </div>
                            <div class="portlet-content lastViewedArticle ">
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text
                                <br>text</div>
                            <!-- portlet-header -->
                        </div>
                        <!-- portlet- -->
                    </div>
                    <!-- moveOnchange-->
                    <div class="face back">
                        <div class="inner">
                            <div class="portlet">
                                <div class="flipForm">
                                    <ul class="list-inline pull-right">
                                        <li class="flipControl" id="save-changes"> <span class="pull-right glyphicon glyphicon-floppy-disk gi-1x opacity7"></span>

                                        </li>
                                    </ul>
                                </div>
                                <!-- Header Closed -->
                                <div class="portlet-content lastViewedArticle ">
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text
                                    <br>text</div>
                                <!--- Portlet content -->
                            </div>
                         </div>
                    </div>
                </div>
            </div>
            <!-- dbContainer2 -->
        </div>
    </div>

Javascript

$('#edit-changes').on('click', function () {
    $('.back').css('transform', 'rotateY(0deg)');
    $('.front').css('transform', 'rotateY(180deg)');
});

$('#save-changes').on('click', function () {
    $('.front').css('transform', 'rotateY(0deg)');
    $('.back').css('transform', 'rotateY(180deg)');
});

$(function () {
    $(".column").sortable({
        connectWith: ".column",
        handle: ".portlet-header",
        cancel: ".portlet-toggle",
        placeholder: "portlet-placeholder ui-corner-all"
    });

    $(".portlet")
        .addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
        .find(".portlet-header")
        .addClass("ui-widget-header ui-corner-all");

    $(".portlet-toggle").click(function () {
        var icon = $(this);
        icon.toggleClass("ui-icon-minusthick ui-icon-plusthick");
        icon.closest(".portlet").find(".portlet-content").toggle();
    });
});

Answer №1

It is important to avoid using the same id's for multiple elements on a single page and instead utilize the class attribute, as you have mentioned.

To access the element that has been clicked, you can use:

var element = $(this)

For more information on these keywords in events like this, take a look at this resource.

Your current process involves finding all elements with the classes 'back' and 'front' and then applying transformations to them.

If you need an element close to the clicked one, you can use the function foo.closest('.back'), which will return the closest element specified by the selector.

Answer №2

After some investigation, I managed to come up with the solution:

I made a slight adjustment to the code as follows:

  $('.edit-changes').on('click', function () {

      $(this).closest('.flip').find('.back').css('transform', 'rotateY(0deg)');
      $(this).closest('.flip').find('.front').css('transform', 'rotateY(180deg)');
  });

  $('.save-changes').on('click', function () {
      $(this).closest('.flip').find('.front').css('transform', 'rotateY(0deg)');
      $(this).closest('.flip').find('.back').css('transform', 'rotateY(180deg)');
  });

Before, the code looked like this:

  $('.edit-changes').on('click', function () {

      $('.back').css('transform', 'rotateY(0deg)');
      $('.front').css('transform', 'rotateY(180deg)');
  });

  $('.save-changes').on('click', function () {
      $('.front').css('transform', 'rotateY(0deg)');
      $('.back').css('transform', 'rotateY(180deg)');
  });

The key was to identify and target the closest parent of the elements we need to manipulate.

Check out the working demo here

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

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Sending numerous data fields via ajax

Here is a link to my code playground: http://jsfiddle.net/barmar/mDfQT/10/ $('.add_options').on('click', function () { $('#variants').append('<div class="some_id"><input type="text" id="prop_name" class=" ...

Converting HTML to CSV using PHP

I need assistance with exporting MySQL fields to CSV. I have successfully exported all fields except the one that contains HTML content. My MySQL table is structured as follows: Name: Address: Profile: The 'Name' and 'Address' fields ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Understanding the specific purpose and functionality of the "next()" parameter in express.js

As a newcomer to express.js, I have been diving into the documentation to understand its nuances. One particular aspect that caught my attention is the next parameter in express middleware, which supposedly triggers the following middleware function for th ...

Assign the value from a drop-down menu to an SQL variable dynamically without the need for a submit button

I am trying to retrieve the value of the selected item in a drop-down menu populated from an SQL database. This value is essential for me to formulate the SQL statement required to access a specific record. The drop-down menu has already been populated. S ...

Tips for positioning div elements with css tables

Is it possible to align the div elements in such a way that the first column element spans two rows, while the second column elements are stacked on top of each other using CSS tables? Below is a snippet of my HTML code: <html> <head><link ...

Starting a Fresh Chapter Upon Successful Form Submission with PHP

I am utilizing PHP to control form elements. If the elements are invalid, I display an error message below them. My issue arises when all form elements are valid, but the page does not redirect to the desired destination page. Instead, it displays an empty ...

Splitting a square into four triangles using CSS styling

My current challenge involves creating a square comprised of 4 triangles of equal size, each with hover events. Here is the CSS I'm using to create the triangles: .right, left, .top, .bottom { position: relative; width: 26px; } .right:before ...

issue with replicated field

My code is working perfectly fine, as you can see here. Now, I am attempting to replace <input id="input1" /> with <div id="input1"> </div>. You can view my progress here. The issue lies in the IDs - they are meant to change from input1 ...

Set the value of one email input to another email input in AngularJS

I'm having trouble trying to link an email input field to another in angularjs without success. Here is what I have attempted so far: <div class="row-fluid"> <div class="control-group span12"> <label for="email">Email</labe ...

List Elements Not Displaying Correctly due to CSS Styling Issues

After spending several hours trying to solve this problem, I've hit a roadblock. The challenge lies in dynamically adding items to a list using JavaScript and the Dojo library. I've experimented with both vanilla JS and Dojo code, ruling that pa ...

Exploring the parent of an HTML element / Finding a child element with unique content

Struggling with a challenge from frontendmentor that involves JavaScript. I need help on making the script detect if a P tag contains 0 as its content and then applying a different style to the containing div. <section class="pledge-box sub-section ...

implementing automatic ajax requests when user scrolls

This is a piece of JavaScript code: $(window).scroll(function() { $.ajax({ type: "GET", url: "not_data.php", data: dataString, success: function my_func () { //show new name ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Learn the process of connecting checkboxes to a database in MeanStack using Angular

Hey everyone, I'm currently working with AngularJS ng-repeat and I am trying to dynamically bind a checkbox based on a true or false value from the database. However, even when the database value is set to true, the checkbox does not automatically che ...

What is the process for converting plain text into an image tag using the methods ".replace()" and ".html()"?

My goal is to customize this particular answer so that it can transform classic BCCode [img]{url}[/img] into an HTML image. In the code snippet provided, I have successfully implemented something similar with [b]text[/b]. However, when attempting to use [i ...

When the left/top/right/bottom properties are not specified, using position:fixed produces the desired results in Firefox and Internet Explorer, but not in Safari

It's unfortunate that I have to bring up another question related to position:fixed, but after going through various other questions and forum threads, I'm still not clear on this particular issue. The code below is a simple illustration of how ...