show the number of likes when click the like button - javascript

I try this concept but it not success, When I click the like button
then count of likes will be increase by 1 again I press that button
then it decrease by 1. For example, Now the count is 5 I click the
like button then the count is 6, again I press now the count is 5
(like Facebook).
JSP
<button class="like_btn" onclick="like()">
<span id="icon"><i class="far fa-thumbs-up"></i></span> <span
id="count">0</span>Like
</button>
JavaScript
function like(){
const likeBtn = document.querySelector(".like_btn");
let likeIcon= document.querySelector("#icon");
let count = document.querySelector("#count");
let clicked = false;
likeBtn.addEventListener("click", () => {
if (!clicked) {
clicked = true;
likeIcon.innerHTML = `<i class="fas fa-thumbs-up"></i>`;
count.textContent++;
}else{
clicked = false;
likeIcon.innerHTML = `<i class="far fa-thumbs-up"></i>`;
count.textContent--;
}
});
}

Related

Add to cart buttons functionality

I have products and a cart. Each product has an "Add to cart" button and when you click it, it'll add the product to the cart and the inner text of the button will be "In cart" and the button will be disabled. My problem is that I can't figure out how to enable the button and change the inner text back to "Add to cart" after I remove the product from the cart or clear it.
This is the JS for adding the product:
let addBtns = document.getElementsByClassName("bag-btn");
for (let i = 0; i < addBtns.length; i++) {
const btn = addBtns[i];
btn.addEventListener("click", addToCart);
}
function addToCart(e) {
const button = e.target;
button.innerText = "In Cart";
button.disabled = true;
const title = button.parentElement.nextElementSibling.textContent;
const price =
button.parentElement.nextElementSibling.nextElementSibling.children[0]
.textContent;
const img = button.parentElement.children[0].src;
addItemToCart(title, price, img);
}
function addItemToCart(title, price, img) {
const newRow = document.createElement("div");
newRow.classList.add("cart-item");
newRow.innerHTML = `
<img src="${img}" alt="product" srcset="" />
<div>
<h4>${title}</h4>
<h5>${price}</h5>
<span class="remove-item">Remove</span>
</div>
<div>
<i class="fas fa-chevron-up"></i>
<p class="item-amount">1</p>
<i class="fas fa-chevron-down"></i>
</div>`;
cartContent.append(newRow);
}
this is the remove product function:
cartContent.addEventListener("click", (e) => {
if (e.target.classList.contains("remove-item")) {
let removeItem = e.target;
cartContent.removeChild(removeItem.parentElement.parentElement);
SO, how to change the button text and functionality back to normal after I remove the product from the cart? Any help would be appreciated.
Why do you not do the same delegation for the add as you do for the remove?
I do not have your HTML, but something like this
cartContent.addEventListener("click", (e) => {
const tgt = e.target;
if (tgt.classList.contains("remove-item")) {
tgt.closest("whatever container").remove();
tgt.closest("whatever container has button").querySelector(".bag-btn").textContent="Add to cart";
}
else if (e.target.classList.contains("bag-btn")) addToCart(tgt)
})
and have
function addToCart(button) {
// const button = e.target;
All those parentElement.nextElementSibling.nextElementSibling.children[0] are horrific
Instead use button.closest("whatever container").querySelector("some selector")

How do i create a system where a user can favourite/unfavourite individual courses on a webpage?

I am trying to create a 'favourites' system where the user can click on a star in the top right of a button to add that course to their list of 'favourites'. Here is the HTML for said button (there are 6 of them and all 6 are the same):
<button class="divflexbuttonitem">
<div class="libraryfaviconcontainer">
<i class="libraryfavicon" onclick="toggleFavourite()"></i>
</div>
</button>
And here is my (attempt at) JavaScript for the toggleFavourite() function:
function toggleFavourite() {
console.log("Running toggleFavourite();");
var favicon = document.getElementsByClassName("libraryfavicon");
var faviconCount = favicon.length;
var favArray = new Array();
var favArrayString = favArray.toString();
var i;
for(i = 0; i < faviconCount; i++) {
favArray.push(favicon[i].id);
}
alert(favArray.length);
alert(favArrayString);
let favourite = false;
if (favicon[i].style.backgroundImage == 'url("libraryfavselected.png")') {
favourite = true;
}
else if (favicon[i].style.backgroundImage == 'url("libraryfavunselected.png")') {
favourite = false;
}
if (!favourite) {
favicon[i].style.backgroundImage = 'url("libraryfavselected.png")';
console.log("Added to Favourites");
}
else {
favicon[i].style.backgroundImage = 'url("libraryfavunselected.png")';
console.log("Removed from Favourites");
}
}
I am trying to get all elements with a specific class name, add them to an array, and call them from an array to change the url of the 'favicon' of the specific favicon that was pressed. However, my code does not work whatsoever and i am lost as to how to correctly code it.
There are better ways to structure this type of application, but here is some really simple code to get you started.
You can see that the fav class is toggled on and off when an item is clicked, and then we can get all the current favourites by querying all elements with the fav class.
const toggleFavourite = (event) => {
if (event.target){
const clickTarget = event.target;
clickTarget.classList.toggle('fav')
}
}
//Example use, get all favs and attach the text as a new element
const getFavs = () => {
const favs = document.querySelectorAll('.fav');
const favContainer = document.querySelector('.favs')
favContainer.innerHTML = "";
for( let fav of favs){
let newFav = document.createElement('div');
newFav.textContent = fav.textContent;
favContainer.appendChild(newFav)
}
}
.fav {
color: red;
}
<i class="" onclick="toggleFavourite(event)">1</i>
<i class="" onclick="toggleFavourite(event)">2</i>
<i class="" onclick="toggleFavourite(event)">3</i>
<i class="" onclick="toggleFavourite(event)">4</i>
<i class="" onclick="toggleFavourite(event)">5</i>
<button id="getFavs" onclick="getFavs()">Get Favs</button>
<section class='favs'>
</section>

Toggling button classes and text

I am trying to change text and icons with jquery. When you click at the button it changes, but when you click the button again it struggles. The icon and the text does not change back to default.
Code behind
string box = "<div class=\"alter-Wrp\"> <div class=\"alert alert-danger {0}\">{1}</div></div>";
if(count > 0)
litAlert.Text += String.Format(box);
asp.page
<button class="btn btn-dangerr btn-lg" type="button"><span class="glyphicon glyphicon-bell beee"></span>
<span class="text">Show Alarm</span> </button>
<asp:Literal ID="litAlert" runat="server"></asp:Literal>
Jquery
$('.btn-dangerr').click( function(e) {
var tgl = $('.btn-dangerr');
var box2 = $('.alter-Wrp');
var icon = $('.glyphicon');
var text = $('.text');
var toggleClass = '.beee';
icon.addClass('glyphicon-bell');
text.text('Show Alarm');
box2.slideToggle(function (){
if (tgl.hasClass(toggleClass)) {
icon.removeClass('glyphicon-bell').addClass('glyphicon-fire');
text.text('Hide Alarm');
} else {
e.preventDefault();
}
$('.btn-dangerr').toggleClass(toggleClass);
});
});
http://jsfiddle.net/w8Yjz/25/
Pretty sure this is what you're trying to do:
$('.btn-dangerr').click(function (e) {
$('.alter-Wrp').slideToggle();
$('.beee').toggleClass('glyphicon-bell glyphicon-fire');
if ($('.beee').hasClass('glyphicon-fire')) {
$('.text').text('Hide Alarm');
} else {
$('.text').text('Show Alarm');
}
});
Fiddle

Show one random icon on page load

How do I show one random icon on page load with js? Below is the HTML code I have:
<span>
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
I need to show only one of the three icons.
My HTML would be
<span id = "mySpan"></span>
You can do this using javascript
var myRand = Math.floor(Math.random() * 3) + 1;
var randString = '';
if(myRand == 1)
randString = 'one';
else if(myRand == 2)
randString = 'two';
else if(myRand == 3)
randString = 'three';
var ele = document.createElement("div");
ele.setAttribute("id","icon-"+randString );
document.getElementById("mySpan").appendChild(ele);
Well , this assumes that your ids have the icon and not the classes
<span>
<i class="fa fa-trash-o" style="display: none;" id="icon-one"></i>
<i class="fa fa-frown-o" style="display: none;" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" style="display: none;" id="icon-three"></i>
</span>
var icons = [ 'icon-one', 'icon-two', 'icon-three' ],
icon = icons[Math.floor(Math.random()*icons.length)];
$( '#' + icon ).show();
This should work if you are using jquery.
use this function to get a random no in range(min, max)
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
and use appropriately to show the tag hide other wise
such as
js
var r = function getRandomArbitary (1, 3);
var eleCategory = document.getElementById("main_div");
var eleChild = eleCategory.childNodes;
for( i = 0 , i<eleChild.length; i++ ){
if(i==r){
eleChild[ i ].style.display='block';
}
else
{
eleChild[ i ].style.display='none';
}
}
html
<span id="main_div">
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
you can use java script here. So if there are only three icons one , two and three.
use random function to generate a number between one two and three
var x= Math.floor((Math.random()*3)+1);
if (x==1)
{
//fetch the div id = "icon-one" and display
}
else if (x==2)
{
//fetch the div id = "icon-two" and display
}
else
{
//fetch the div id = "icon-three" and display
}
Although this will work way better if you can rename your id's two icon1,icon2 and so on
it will just be this then :
var x= Math.floor((Math.random()*3)+1);
var icon = "icon";
var id = icon.concat(x);
Simple work woth using jQuery.
Working jsFiddle

How can I change the visible / hidden property of a button with javascript?

On my page I have the following theme change buttons:
<button class="small theme" name="darkBlue" onclick="setThemeColor(this)">
<span style="color: white; font-weight: bold;">#</span>
</button>
<button class="small theme" name="black" onclick="setThemeColor(this)">
<span style="color:black; font-weight:bold;">#</span>
</button>
I have this javascript:
<script type="text/javascript">
if (localStorage.themeColor) {
document.getElementsByTagName('html')[0].className = localStorage.themeColor;
}
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var themeButton in themeButtons) {
themeButtons[themeButton].disabled = false;
}
button.disabled = true;
}
</script>
This always shows the two buttons but I would like to so that instead of the
current button being disabled then the button is not visible. Can someone
suggest how I could do this?
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var themeButton in themeButtons) {
themeButtons[themeButton].disabled = false; // Re-included from original code
themeButtons[themeButton].style.visibility="visible" // Corrected from original answer
}
button.disabled = true;
button.style.visibility="hidden" // Added/Moved from above after noted I'd messed up the logic
}

Categories

Resources