Comprehensive JavaScript JSON details

As a newcomer to the world of Javascript, I've set myself the challenge of creating an online sales platform. To get started, I'm using the fakestore.com API to populate my site with products. Here's a snippet of my current JavaScript code:

var bestSellers = document.getElementById('mVentes');
var test = document.getElementById('test');

// Making a request to fetch the JSON data of products from fakestore.com
var requestURL = 'https://fakestoreapi.com/products';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();

request.onload = function() {
  var superHeroes = request.response;
  mSales(superHeroes)
}

// Function to create cards displaying information for the first 3 products
function mSales(prod) {
  for (var i = 0; i < 3; i++) {
    var card = document.createElement('article');
    var image = document.createElement('img');
    var title = document.createElement('h3');
    var description = document.createElement('p');
    var price = document.createElement('h4');
    var button = document.createElement('button');

    title.textContent = prod[i]['title'];
    image.src = prod[i]['image'];
    price.textContent = prod[i]['price'] + " €";
    button.textContent = "Add to Cart";

    // Truncating long descriptions to only display the first 100 characters
    var desc = prod[i]['description'];
    var text = "";
    for(var b = 0; b < 100; b++) {
      text = text + desc[b] ;
    }
    description.textContent = text + "...";

    card.appendChild(image);
    card.appendChild(title);
    card.appendChild(description);
    card.appendChild(price);
    card.appendChild(button);
    bestSellers.appendChild(card);
  }
}  
...

If someone could help me figure out how to retrieve product information when clicking the "Add to Cart" button, that would be greatly appreciated! PS: Apologies in advance for any awkward translations - French is my primary language! :)

Answer №1

We can store the product ID as a data attribute on the card for easy access.

When adding a product to the cart, we retrieve the product ID from the data attribute, demonstrated in the following code snippet. We can then either make an API call (https://fakestoreapi.com/products/{id})—for example, —or if we're caching API results, filter items based on the product ID. HTML

<article data-id="1">
<img src="example-image" alt="product-image" />
  <h3>title</h3>
  <p>description</p>
  <h4>$123</h4>
  <button onClick="addToCart(event)">
    Add to cart
  </button>
</article>

JS

function addToCart(e){
    const id = e.target.parentNode.dataset.id;
    const url = `https://fakestoreapi.com/products/${id}`;
    //make api call or get from cache and handle logic for cart display
}

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

Obtain the URL linked to the button that was just clicked

As a newcomer to jQuery, I have a question: For instance, on a webpage with a voting feature, when a button is clicked, a counter is increased by +1. Now, how can the URL of this button be displayed on a website? This way, if the URL is shared with others ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

What is the CSS technique to make text wrap around an image, similar to the layout seen in certain newspapers?

I am looking for a way to have my images wrap with text align in this specific layout: <html> text text text text text <br> text text text text text <br> ______________ text text text <br> image | text text text <br> i ...

What causes Post back to be triggered upon closing the page but not when the user navigates away from it?

My code is set up to detect user navigation or closing of the page. It triggers a post back on close, but not when the user navigates away. Strangely, if I include an alert message, it is triggered at all times. Also, there is a timer on the page that is ...

The functionality of the disabled button is malfunctioning in the Angular 6 framework

Just starting out with angular 6 and I'm using formControl instead of FormGroup for business reasons. app.component.html <button class="col-sm-12" [disabled]="comittee_Member_Name.invalid && comittee_Member_Number.invalid && c ...

What is the best way to loop through an array of objects and visually represent each object in a chart?

I'm currently working on developing a React-based dashboard. The initial step involves displaying data from my local API. This information is retrieved from the front end using ComponentDidMount and then filtered to include only the METRIC = SPEND cat ...

jQuery and CSS3 for importing and customizing text files

I successfully customized the file input utilizing jQuery and CSS3. However, there is one aspect I couldn't quite figure out. After the user selects an image or file, I want to display the selected file's text at the very bottom of the text like ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Can a perhaps clause be incorporated into an xpath?

Is it feasible to incorporate an optional locator in the xpath, as suggested by the title? For instance, consider the following HTML structure: <div> <h2>Some Text</h2> <h2><span>Some Text</span></h2> < ...

When attempting to reference from a variable, you may encounter an error stating that setAttribute

In my VueJS project, I am facing an issue with dynamically adding the width attribute to an inline SVG code stored in a variable called icon. Despite having the correct SVG icon code in the variable, the setAttribute method is not working as expected and t ...

Tips for displaying the Font Awesome icons

I have included Font Awesome icons within the <span> tags and applied the necessary styles in my CSS file. However, the icon is not being displayed correctly. I am looking for a solution to ensure the correct display of the icons. The HTML code wher ...

Simplified method of connecting dynamic components without needing to remember functions in jQuery

I have a page where users can freely move, resize, and modify content. The basic setup is as follows: $('.element').on().resizable().draggable(); When this code is called on page load, it allows elements to be resizable and draggable. The issu ...

Adjusting the position alters the dimensions of the image

Looking to position an emoji-panel in the bottom right corner with dimensions relative to the screen width. Everything works fine when position is set to not fixed (see first image). However, switching the position to fixed causes strange changes to both ...

Unusual problem encountered on mobile devices with custom font-face and Font Awesome font combination

Experiencing difficulties with font-face implementation on mobile devices. The custom font-face definition for the Rex font is as follows: @font-face { font-family: 'RexBold'; src: url('RexBold.eot?#iefix') format ...

Enhance your Three.js experience: Effortlessly Panning Panoramas with Smooth E

I am currently working on a 6 cube panorama project and using this demo as a reference: The dragging functionality in this demo is controlled by mouse events. I am looking to implement easing so that the panorama cube follows the mouse smoothly. I underst ...

Chrome: When enlarging an image, the overflow of the outer div is disrupted

My image wrapper is designed to hide overflow when hovered over. It works well in Firefox and Opera, but Chrome displays it strangely. I've created a 10-second screen recording to demonstrate the issue. Watch it here: I also tested it on JSFiddle, ...

The border class in Bootstrap 4 seems to be malfunctioning when it comes to the top

I'm struggling to add a border to a div using Bootstrap 4. When I try using only the border property, it looks strange, and when I use other properties, no border appears. Here is the code snippet: I even tried with the beta 2 version. If there is s ...

Discover how to reveal a hidden div tag upon hovering over a different div tag using CSS

I have a minor issue that I need help with. I want to achieve an effect where one div is displayed when another div is hovered over in CSS. Once the cursor is removed, the second div should be hidden again. How can I accomplish this? There is a second hid ...