Tips for toggling the appearance of like and add to cart icons

I am attempting to create a simple functionality for liking and adding items to a cart by clicking on the icons, which should immediately change the icon's color when clicked. However, I am facing an issue where the parent div's link is also being triggered, so I added a stopPropagation to the script. I have not yet added the code for #addtocart in html & script as it will be similar to the #heart like icon function.

The problem I am encountering is that the toggle is not working properly, and my editor is showing an "Error: $undefined" message even though I have linked my javascript correctly. If someone could help me identify where I went wrong, I would greatly appreciate it. In the future, I plan to implement the functionality where clicking on these icons will add the product to the user's wishlist or cart page, but since I haven't learned backend coding yet, I am focusing on rendering the UI for now. It would be great if you could provide guidance on how to make the icons link directly to the user's wishlist or cart page without inheriting the parent's link.

$(document).ready(function() {
  $('#heart').click(function() {
    $('#heart--liked').toggle('1000');
  });
  $("#heart a").click(function(e) {
    //do something to stop link # from loading
    e.stopPropagation();
  });
});
... (omitted CSS styling) ... (omitted HTML with fontawesome icons)

Answer №1

It's recommended to utilize a class that changes the color upon clicking.

Take a look at the functioning snippet below where I have made adjustments respecting your approach:
I integrated CSS variables to the body for seamless operation and included comments for modifications.

$(document).ready(function() {

  // Custom code for toggling heart fill
  $("#heart--liked").click(function(e) {
    $(this).toggleClass("far").toggleClass("fas"); // Toggles the filling effect!
  });

  // Behavior on link click (color change)
  $(".product__list__item--icons a").click(function(e) {
    e.preventDefault(); // Prevent default action of link (# from loading)
    $(this).toggleClass("selected"); // Toggles the colored class!
  });

});
.product__list__item {
  border-radius: 2px;
  background-color: var(--pure-white);
  border: solid 1px var(--dark-grey);
}

.product__list__item--description {
  padding: 1.5rem;
  text-align: left;
}

/* Other styles remain the same */

.product__list__item--description:after {
  content: "";
  display: table;
  clear: both;
}
<html>

<head>
  <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.11/css/all.css" integrity="sha384-p2jx59pefphTFIpeqCcISO9MdVfIm4pNnsL08A6v5vaQc4owkQqxMV8kg4Yvhaw/" crossorigin="anonymous">
</head>

<body style="--middle-grey: #888; --dark-grey: #444; --light-pink: #ffb6c1; --pink: #dd888b;">
  <div class="product__list__item">
    <a href="#" class="image-container">
      <div class="image-container__wrapper">
        <div class="image-container--mask">
          <h4>View details</h4>
        </div>
        <img src="https://foter.com/photos/235/design-tree-home-acapulco-lounge-chair-yellow-1.jpg?s=pi" alt="yellow chair">
      </div>
      <div class="product__list__item--description">
        <h3>Yellow Chair<sup class="price--hot">Clearance!</sup></h3>
        <div class="product__list__item--icons">
          <span id="heart"><a href=" "><i id="heart--liked" class="far fa-heart fa-2x"></i></a></span>
          <span id="addtocart"><a href=" "><i class="fas fa-cart-plus fa-2x"></i></a></span>
        </div>
        <div class="product__list__item--price price--hot">$189
          <sub class="price__sale">$109</sub>
        </div>
      </div>
    </a>
  </div>
</body>

</html>

Trust this makes it clearer.

Answer №2

The variable $ remains undefined due to the presence of brackets around the name, resulting in multiple nameless variables...

   $document.ready(function() {
      $heart.click(function() {
        $heart-liked.toggle('1000');
      });
      $heart.a.click(function(e) {
        e.stopPropagation();
      });
    });

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

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

Utilize a pre-defined layout in a Vue component that is sent as a property

As a complete beginner, I kindly ask for your patience as I navigate through the coding basics. I am looking to utilize a template specified in the prop. The template is located within the DOM. My intention for approaching it this way is to reuse the comp ...

Problem with user scalability in desktop browsers: when zooming out to 33% and lower, all CSS vanishes

Having trouble understanding why my styling disappears at 33% zoom on Chrome and even worse at 75% on IE11. <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"> <meta name="viewport" content="w ...

``Is it possible to retrieve the value of an <option> tag in a Django view?

My form includes an option to select the country you are coming from. Within my model, I have a field called country_living with the following choices: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', &ap ...

Transferring an image file from PHP to JavaScript

I have encountered an issue with transferring images stored as LONGBLOB files in my database to a JS file for dimension comparison with the screen. Here is how I retrieve the images: function fillArrays(){ $idArray = array(); $sql = "SELECT oglas_id,s ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

Exploring the process of extracting a nested JSON value using Postman

I am currently facing an issue with parsing the json response from a post request, and then sending the parsed data to a put request. Here is the response body: { "createdBy": "student", "createdOn": "2019-06-18", "Id1": "0e8b9 ...

How can I dynamically update the URL parameter based on the selected option in a dropdown list?

There is a single select option box with three options. When a user selects an option, the corresponding value should be appended to the URL (e.g., value=needbyDate). If another option is selected later, the previous value in the URL should be replaced w ...

Is there a way to fetch the version of my npm application without pulling in additional package.json details?

I am working on a Single Page Application (SPA) using React and built with Webpack as part of create-react-app. In my application, I display the version number fetched from package.json like this: import npmInfo from 'package.json' ... <div c ...

Is there a way to assign a null value to an empty material UI text field when submitting the form, rather than an empty string?

One issue I am facing is that the default value of the text field is zero, but when I submit the form, the value of the text field becomes an empty string instead. This is not the intended behavior as I want the value to remain zero in the end. How can I r ...

Tips for utilizing the radio type in ng-repeat and deciding on the appropriate ng-model

I have 10 inquiries for a survey, each requiring a yes or no response. I want to utilize radio options and display these questions using ng-repeat. How can I achieve this? What should I set as the ng-model for each question? <form> <div ng-init= ...

Can Datatables be incorporated with modal pop-ups for editing purposes?

I am dealing with a DataTable that fetches data from a remote server. Each cell in the table has a mouse-over link that can trigger a modal popup (all links are the same). The issue I'm facing is the inability to pass the unique ID of the row and the ...

JavaScript and DOM element removal: Even after the element is removed visually, it still remains in the traversal

Our goal is to enable users to drag and drop items from a source list on the left to a destination list on the right, where they can add or remove items. The changes made to the list on the right are saved automatically. However, we are encountering an iss ...

AngularJs JSON endpoint modifier

I've been working on a simple weather app in Angular for practice, but I've hit a roadblock. Here's the Angular JSON feed I'm using: app.factory('forecast', ['$http', function($http) { return $http.get('http: ...

Ways to display information using a show/close button in React

I am currently immersed in the learning process of React. My goal is to display information about different countries using a toggleable button. However, I have encountered some obstacles along the way. There's an input field that triggers upon enteri ...

Getting access to the properties of an array containing objects

Check out the data below: [ { "name": "Fluffy", "species" : "rabbit", "foods": { "likes": ["carrots", "lettuce"], "dislikes": ["seeds", "celery"] } }, { "name": "Woofster", "species" : "dog", "foods": { ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...