jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/

Let me explain the functionality of the code

The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second container starts empty.

When you hover over each .item, you will see bootstrap glyphicons in the shape of hearts.

If you click on an .item, it will move to the .second container. When you hover over the .item in the .second container, the heart glyphicon will change to a minus sign.

Although the code looks good, there is a small issue with the jQuery part.

In the current implementation, all clicks on the .item container trigger a clone() action to the .second container. However, the desired behavior is to only trigger the clone() when clicking on the glyphicon inside the .item container. Here is where I need help tweaking the jQuery code.

Should I use the parent() method or another jQuery method like closest() or has()? Your assistance would be greatly appreciated.

Please assist me with resolving this issue.

Answer №1

To make the .gliphicon clickable, simply select the .item and use it in place of $(this). Check out the updated jsfiddle for reference:

$(document).on('click', '.glyphicon', function() {

var item = $(this).closest(".item");

if(item.parent().attr("class") == "itemList") {
    item.clone().appendTo('.second');
    $(this).prop('disabled', true);
    item.css({"opacity": "0.2", "-webkit-user-select": "none"});
}
else { //NEW ELSE
    var i = $('.itemList').find('[data-state="' + item.data('state') + '"]');

        i.css({"opacity": "1", "-webkit-user-select": "true"});
        i.find(".glyphicon").prop('disabled', false);

    item.remove();
}


});

Answer №2

Simply add a data-attribute as an extra, no other changes were made in the HTML. I also included event binding for elements with the class glyphicon-minus-sign.

When removing the element, make sure to use .closest('.item') because using $(this).remove() will remove the icon.

Here is an alternative way to rewrite your logic:

HTML:

<div class="first">
  <div class="itemList">
    <div class="item elem" data-state="loren">
      <div class="desc">Loren Ipsum Dolor</div>
      <div class="icons">
        <i class="glyphicon glyphicon-heart"></i>
        <i class="glyphicon glyphicon-minus-sign" data-state="loren"></i>
      </div>
    </div>
    <div class="item elem" data-state="sic">
      <div class="desc">Sic Amet</div>
      <div class="icons">
        <i class="glyphicon glyphicon-heart"></i>
        <i class="glyphicon glyphicon-minus-sign" data-state="sic"></i>
      </div>
    </div>
  </div>
</div>
<div class="second"></div>

JS:

$(document).on('click', '.elem, .glyphicon-minus-sign', function(e) {
  e.stopPropagation();
  if ($(this).parent().attr("class") == "itemList") {
    $(this).removeClass("elem");
    $(this).clone().appendTo('.second');
    $(this).prop('disabled', true);
    $(this).css({
      "opacity": "0.2",
      "-webkit-user-select": "none"
    });
  } else {
    $('.itemList')
      .find('div[data-state="' + $(this).data('state') + '"]')
      .prop('disabled', false)
      .css({
        "opacity": "1",
        "-webkit-user-select": "true"
      }).addClass("elem");
    $(this).closest('.item').remove();
  }
});

DEMO

Answer №3

One approach you could take is to utilize the parents selector in jQuery. In this case, if the parent of your glyphicon has a class of 'icons' and is located at position 0, you can implement the following logic:

$(document).ready(function(){

    $(".glyphicon").click(function() {
        if($(this).parents().eq(3).attr("class") == "itemList") {
          $(this).clone().appendTo('.second');
          $(this).prop('disabled', true);
          $(this).css({"opacity": "0.2", "-webkit-user-select": "none"});
        }
        else {
        $('.itemList')
          .find('[data-state="' + $(this).data('state') + '"]')
          .prop('disabled', false)
          .css({"opacity": "1", "-webkit-user-select": "true"});
        $(this).remove();
        }
   });

});

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

Substitute using JQuery

Hello, I am attempting to update some html using Jquery, here is my current progress. $(".old").html($(".new").html()); It's almost working. The problem is that the .new content is being copied instead of replaced. I want to Cut/Paste instead of Co ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

WebDriver encounters difficulty clicking on a certificate error popup window

Currently, I am using webdriver 2.40.0 in C# to interact with my company's website. The issue arises when I encounter a certificate error page while trying to access certain elements. Specifically, after clicking the override link and entering some in ...

Can HTML variables be accessed in lines of code before they are declared in HTML?

In line 1 of my code, I am trying to access the rowData variable which is declared in the second HTML line. However, I keep getting the error message "Property 'rowData' does not exist on type 'AppComponent'" for that line. Strangely, t ...

How can I distinguish the search results from the while loop section at the bottom of the page?

One issue here is the footer's margin position being influenced by the results of the while loop. To see the problem more clearly, visit this link: Below is the code snippet: <div id="print_output1"> <?php $co ...

Difficulty encountered with altering background color of table row in Firefox using CSS

I'm facing an issue with styling table rows that have alternating classes - I want to highlight the row that is being hovered on using CSS. Below is the CSS code I have implemented: .gridrowclass1 { background-color : #bbb00b } .gridrowclass1:h ...

Can a `react` app with `mysql` be uploaded to `github`?

I recently created a basic online store with the help of react, node, and mysql. I am considering uploading it to github, but I'm uncertain if I can do so while my database is currently stored on localhost. Any advice? ...

Adding Font Awesome to my Angular 12 project within Visual Studio 2019

Seeking a no-frills guide for integrating Font Awesome (free version) into my Angular 12 application within Visual Studio 2019. After countless Google searches, I am bombarded with intricate methods. It's baffling why such complexity exists just to in ...

Unable to load CSS in Node.js when the parameter in Express.js is too long

I have been working on an application using Node.js, express.js, and ejs. I am utilizing the following code to incorporate ejs and load css: app.engine('.html', require('ejs').__express); app.set('views', __dirname + '/vi ...

Place an element in relation to the vertical size of a div that includes written content

Currently, I am working on implementing a button with a popup that appears underneath it when the user hovers over it. The specific requirements for this setup are: The size of the button should not affect the size of the popup The popup should always be ...

javascript guide on converting an array into the correct JSON format

I'm working with an array that has the following structure: var arr = [ [{a:1}], [{b:1}], [{c:1}], [{d:1}], [{e:1}] ] My goal is to format it into the proper format as shown below: [{a:1},{b:1},{ ...

Use Javascript to toggle the display to none for a specific table row (tr)

Is there a way to implement JavaScript code that will hide a specific table row using display:none;, and then reveal it again when a button is clicked? ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...

How can I show PHP retrieved data in separate text areas?

Struggling to retrieve values from the database? Simply select an employee ID using the 'selectpicker' and watch as the corresponding name and salary are displayed in the textarea. So far, I've managed to set up the following HTML Code: &l ...

What is the best way to assign a unique ID to every element in this situation?

Here is the given code: var words = ['ac', 'bd', 'bf', 'uy', 'ca']; document.getElementById("wordTable").innerHTML = arr2tbl(2); function arr2tbl(ncols) { return words.reduce((a, c, i) => { ...

Managing multiple carousels simultaneously using the middle mouse button in Swiper.js

I am currently utilizing 5 carousels on my screen, all of which are operated by the same navigation buttons. In addition to this, I require the ability to control them using the middle mouse scroll. However, when I activate the mouse wheel control, only ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

How can you display a doughnut chart with a custom color to represent empty or no data, including doughnut rings?

I have integrated a doughnut chart from chartjs into my Vue project using vue-chartjs. Currently, the doughnut chart does not display anything when there is no data or all values are empty. Is there a way to customize the color and show the entire doughnu ...

Display or conceal a vue-strap spinner within a parent or child component

To ensure the spinner appears before a component mounts and hides after an AJAX request is complete, I am utilizing the yuche/vue-strap spinner. This spinner is positioned in the parent days.vue template immediately preceding the cycles.vue template. The ...