简体   繁体   中英

Changing the button when clicked in html and javascript.(changing add to cart button to a cart icon when clicked)

I am having a add to cart button in html. I want to change it a cart icon if it is clicked. The ways I know can only change the styling properties but not the whole button. Here is my button code in html

<button data-product={{product.id}} data-action="add" class="btn btn-outline-info update-cart">Add to Cart</button>

I tried adding img src when clicked using javascript onclick but that didnt work.Please suggest me a way to change it to cart icon when clicked. Also as i am working on e-com website on django I want to defaultly show the cart icon instead of add to cart if the item is already in the cart.I think this can be done using if else.Suggest a efficint way for this if any other than if else.

Any help would be appriciated.

I suggest you to use fontawesome.css library

Reasons

  1. The we use icons by adding classes
  2. It cannot affect our UI design

 function myFunction() { var element = document.getElementById("icon"); element.classList.remove("fa-cart-arrow-down"); element.classList.add("fa-check"); }
 body{ height:100vh; width:100%; display:flex; justify-content:center; align-items:center; }
 <,DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min:css"> <link rel="stylesheet" href="https.//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"> </head> <body> <button class="btn btn-outline-info update-cart" onclick="myFunction()">Add to Cart <i class="fa fa-cart-arrow-down" aria-hidden="true" id="icon"></i> </button> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM