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

Prior to stacking the divs, separate the line within the div

In the process of creating a responsive navbar with Bootstrap, I encountered an issue. When resizing the window to a smaller size, the collapse icon shifts from the top right position below my "logo". Here is how the site appears on a regular screen: http ...

What is the best approach to removing a component by utilizing the children prop in React?

I am currently working on a specific scenario: In my project, I have a component called Foo with a property named bar If the bar property is set to true, then I need to display the Bar component that is nested inside the Foo component If the bar prop ...

In CSS, when text within a tab div lacks spaces, it triggers a horizontal scrolling effect

My special css style for the div: .message-body { background: #5181a2; padding: 8px 5px; text-align: justify; } I aim to display this particular text inside the div similar to how 'hello hello' appears on the line above. ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Obtain the details of a selected item in a list by tapping on it using Natives

I am wondering how to retrieve the context of a tapped item in a listview. For example, if there are three items in the list, how can I determine that the second item was clicked and access the data related to that item in the observable array? For instan ...

Is there a way to adjust the label size for a material ui TextField component?

My TextField element is defined like this: <TextField id="standard-with-placeholder" label="First Name" className={classes.textField} margin="normal" /> It currently appears as shown in the image below: However, I would like it to look mor ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

Essential symbol needed for labeling the user interface element

My HTML includes a dynamic label component where the 'required' value is determined by an API response that can be either true or false. Is it feasible to assign the property ojComponent{ required: true } for this label? *Date From ---- To --- ...

What is the best way to trigger a jQuery function once a form has been successfully submitted?

Is there a way to execute a jQuery function AFTER a form has been submitted? I am familiar with calling a function ON submit, but I specifically need it to run after the form data has been posted and stored in the database using PHP. In my website projec ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Checking for the winner in a JavaScript tic-tac-toe game

Here is the code snippet for a tic-tac-toe game: $(".square").one("click", function() { if( gameOver == false ) { sq1 = $("#sq1").text(); // captures the value of squares after being clicked. sq2 = $("#sq2").text(); //and so on for all 9 squares } / ...

AngularJS Login Popup with SpringSecurity

I have successfully integrated spring security with my AngularJS webpage utilizing Rest API. However, I am facing an issue where every time I attempt to log in using the rest api from my customized login page, it prompts me for the login credentials in a p ...

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

Switching between links while using Vue Router may cause jQuery to become disabled

I am currently utilizing vue router to facilitate navigation on my website. Within this setup, I have various pages such as a home page and an about us page. The issue I am facing pertains to some jQuery functionality that is implemented in a separate JS f ...

Making multiple Node.js requests using the request module: A comprehensive guide

Purpose: My goal is to extract data from approximately 10,000 web pages using Node.js. Issue: The scraping process speeds through the first 500~1000 pages but then significantly slows down beyond that point, sometimes halting completely. To initiate the ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...