How to change image on hover of multiple images - javascript

I have a list of images and I want to be changed when I hover on it and then change back to the previous image on mouse leave. and each image is different. I have done it but it's not the right way of doing it. and I couldn't figure out the right way.
//html code: its actually long list but I'm just showing two of the list//
<li>
<div class="card">
<img class="my-img" id="my-img1" src="./images/AMH010301_G-1-dresslink.jpg" alt="Denim Jeans"onmouseover="hover1()" onmouseout="offhover1()">
<h1>Lorem1</h1>
<span class="price-first">$24.99</span>
<span class="price">$17.99</span>
<br>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<p>Lorem ipsum dolor sit amet..</p>
<button class="add-to">Add to Cart</button>
</div>
</li>
<li>
<div class="card">
<img class="my-img" id="my-img2" src="./images/AMH010327_W-1-dresslink.jpg" alt="Denim Jeans" onmouseover="hover2()" onmouseout="offhover3()">
<h1>Lorem2</h1>
<span class="price-first">$24.99</span>
<span class="price">$14.99</span>
<br>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<p>Lorem ipsum dolor sit amet..</p>
<button class="add-to">Add to Cart</button>
</div>
</li>
//javascript code//
function hover1() {
document.getElementById("my-img1").src = "./images/AMH010301_G-5-dresslink.jpg";
}
function offhover1() {
document.getElementById("my-img1").src = "./images/AMH010301_G-1-dresslink.jpg";
}
function hover2() {
document.getElementById("my-img2").src = "./images/AMH010327_W-5-dresslink.jpg";
}
function offhover2() {
document.getElementById("my-img2").src = "./images/AMH010327_W-1-dresslink.jpg";
}
function hover3() {
document.getElementById("my-img3").src = "./images/AMH011122_W-3-dresslink.jpg";
}
function offhover3() {
document.getElementById("my-img3").src = "./images/AMH011122_W-1-dresslink.jpg";
}
function hover4() {
document.getElementById("my-img4").src = "./images/AMH011200_W-3-dresslink.jpg";
}
function offhover4() {
document.getElementById("my-img4").src = "./images/AMH011200_W-2-dresslink.jpg";
}

Although what you've done works fine, the code looks a bit messier. The solution for a clean, well-organized code would be like this. First, you should consider that you can use a single javascript function to handle all 8 events since they belong to a related logical group. for example, you should have used a javascript function and use the e event param to identify the event triggered and then use a switch or any other suitable control structure to handle the events from different UI elements.
NOTE: another approach that I would recommend is using jquery library. Because it is optimized for this type of things.

Here's how I would do something like this with event listeners and a really simple swapping function. You could also do this with CSS which may be optimal depending on your case.
window.onload = function bindEvents(){
var img1 = document.querySelector('#my-img1');
img1.addEventListener('mouseover', function(){swapImage(img1, "./images/AMH010301_G-5-dresslink.jpg")});
img1.addEventListener('mouseout', function(){swapImage(img1, "./images/AMH010301_G-1-dresslink.jpg")});
}
function swapImage(el, elImg) {
el.src = elImg;
}

Related

Font Awsome icons not showing when I add them using javascript

I'm trying to use Font Awsome in my web poject,
I've added the link:
<script src="https://use.fontawesome.com/bedf006dec.js"></script>
When I add font awesome directly to my HTML like this:
<div class="topbar">
<div class="topbar__elements container">
<div class="topbar__left">
<a href="#">
<i class="fa fa-map-marker" aria-hidden="true"></i>
<span> Middle East Airlines Ground Handling</span>
</a>
<a href="mailto:meag#meag.com.lb" target="_top" rel="noopener noreferrer">
<i class="fa fa-envelope" aria-hidden="true"></i>
<span> meag#meag.com.lb</span>
</a>
<a href="tel:00961 1 622700">
<i class="fa fa-phone" aria-hidden="true"></i>
<span> +961 1 622700</span>
</a>
</div>
<div class="topbar__right">
Career
Contact Us
</div>
</div>
</div>
It works fine:
I'm also using tiny slider and I want to change the text of the previous and next buttons to have Font Awsome icons, I know that I can create custom buttons with tiny slider directly in the HTML code but I'm trying to use the default controls of tiny slider, therefore to try and change the text of these 2 buttons I'm using javascript:
const prevBtn = document.querySelector(".tns-controls").firstChild;
const nextBtn = document.querySelector(".tns-controls").lastChild;
prevBtn.innerHTML = "<i class='fa-solid fa-angle-left' aria-hidden='true'></i>";
nextBtn.innerHTML = '<i class="fa-solid fa-angle-right" aria-hidden="true"></i>';
But it doesn't work and give me this:
Even though when I open the developer tools it looks like as if it worked.

How to trigger the same button to increment and decrement the counter by 1?

I have a javascript function that increment a counter by 1 on onclick event.
<div class="detail-banner-btn heart">
<i class="fa fa-heart-o"></i>
<span data-toggle="I Love It">
<a onclick="like()"> Give Heart </a>
</span>
</div>
<i class="fa fa-heart"></i> <strong id="totalLikes" > 0 </strong> people love it
<script>
function like() {
var a = document.getElementById("totalLikes").innerHTML = +1;
}
</script>
I want the number to be increment by 1 at first click and on second click it needs to be decremented by 1 and so on.
Try following code
<div class="detail-banner-btn heart">
<i class="fa fa-heart-o"></i> <span data-toggle="I Love It"> <a onclick="like()"> Give Heart </a></span>
</div>
<script>
var isLiked=false;
var a=0;
function like()
{
isLiked=!isLiked;
if(isLiked) {
a = document.getElementById("totalLikes").innerHTML = parseInt(a)+1;
}
else {
a = document.getElementById("totalLikes").innerHTML = parseInt(a)-1;
}
}
</script>
<i class="fa fa-heart"></i> <strong id="totalLikes" > 0 </strong> people love it
Let's assume that you have a like button, a comment button, and an area for likes, such as the code below:
<a href="#" id="like-btn" class="card-link">
<i class="fa fa-heart"></i>
</a>
<a href="#" class="card-link">
<i class="fa fa-comment"></i>
</a>
<p>Likes <span>0</span></p>
It would make sense to use jQuery here, and simply update the likes by setting a counter in the JavaScript section of your code (or in a separate file). This way, you don't have to convert the counter to an integer (or number type in JavaScript), or any of that. This is where jQuery makes things much more simple.
var likes = 0;
$('#like-btn').on('click', function() {
if(likes % 2 === 0) {
likes++;
$('span').text(likes);
}
else {
likes--;
$('span').text(likes);
}
});
This why you can just increment the number of likes in a more simple way. If the number has no remainder after being divided by 2, you know it is even, and needs to be incremented (and will increment on your first click), otherwise it will be deincremented.

Dynamically determine which button of a particular class has been clicked with jquery

A demo of my dilemma here
Let's say I have the following html:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<body>
<div class="main" id="thingSection">
<h1>
Test Header
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content1">
Some content
</div>
</div>
<hr />
<div class="main" id="thingSection1">
<h1>
Another Test
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content2">
Some content
</div>
</div>
<hr>
<div class="main" id="thingSection2">
<h1>
Another test, you say?
</h1>
<button class="btn-icon"><i class="fa fa-fw fa-lg fa-windows"></i> <i class="fa fa-fw fa-lg fa-toggle-off"></i> <i class="fa fa-fw fa-lg fa-apple"></i></button>
<div class="content" id="content3">
Some content
</div>
</div>
</body>
</html>
I am using the following jquery to change the toggle icon from FontAwesome from off to on:
$(function() {
$('.btn-icon').click(function() {
if ($(this).find($(".fa")).hasClass('fa-toggle-off')) {
$("i.fa-toggle-off").toggleClass('fa-toggle-on');
} else {
$("i.fa-toggle-on").toggleClass('fa-toggle-off');
}
});
});
When I click the button to toggle the icon, it works as expected, i.e. it changes all of the buttons on the page. However, I would like to dynamically determine which button has been pressed, and then change the content of a child div based on the position of the switch.
I want to avoid hardcoding id's for each button to avoid a ton of if/else statements in the script that must be updated each time I, say, add a new button or a new section. That is to say, I want to dynamically detect which button has been pressed, and affect only that button and its children.
I've noticed that console.log(this) yields only the HTML for the particular button that has been pressed, not all of the buttons.
I'm a novice with jquery. I haven't been able to find a solution to this problem yet, and I feel like there has to be a way to do this dynamically without hardcoding IDs.
EDIT: I've accomplished (partially) what I want to do with the following code:
$(function() {
$('.btn-icon').click(function() {
var t = $(this).find('.is-toggle');
if (t.hasClass('fa-toggle-off')) {
t.addClass('fa-toggle-on');
t.removeClass('fa-toggle-off');
}
else {
t.addClass('fa-toggle-off');
t.removeClass('fa-toggle-on');
}
});
});
Looks like I just didn't understand what exactly $(this) was (:
All you need is $(this) that selects the element that triggered the event. From there you can select down to the div you want.
EDIT: Here is how that might look in code, I pulled this from your fiddle and edited it
$(function() {
$('.btn-icon').click(function() {
$(this).children('.fa-toggle-off, .fa-toggle-on').toggleClass('fa-toggle-on fa-toggle-off');
});
});

Problem selecting correct value from array and assigning to variable

Problem:
I am writing a tracking electron app where the user data is stored on a local JSON file. Essentially i have the cards (user info from json) loaded to display via html. My next step is to run the python backend, problem i am having is I currently can't load the correct array value, only the last one is currently loading into a variable that im trying to pass to python. Since im using forEach i shouldn't have to count or do i still need to do that?
What I expect to happen:
I want an alert to pop up with the current user.handle value. What happens now is it only pops up the last value in the array regardless of which card i press. How can i make each button press trigger the corresponding handle value?
When i test and swap out onclick="myFunction11()" with onclick=alert('${user.handle}') it prints the correct handle value. So i can assume i am just overwriting var city every time and left with the last one in the array. Any advice on how to correctly have myFunction11 pull the corresponding handle value i would love. thanks
Question:
How can i correctly have myFunction11 pull the correct handle value from the array? or is there a better way to achieve this?
Code:
$(document).ready(function() {
users.forEach(function(user) {
$('.team').append(`<div class="card">
<figure>
<img src="${user.image}" />
<figcaption>
<h4>${user.name}</h4>
<h5>${user.handle}</h5>
</figcaption>
</figure>
<div class="links">
<i class="fa fa-pencil"></i>
<i class="fa fa-truck"></i>
<i class="fa fa-trash-o"></i>
</div>
<div class="task">
<div>
</div>
</div>
<div class="bottom-links">
<i class="fa fa-pencil"></i> EDIT
<i class="fa fa-truck"></i> TRACK
</div>
</div>
<script>
function myFunction11() {
var city = '${user.handle}';
alert(city);
}
</script>
`);
});
Adding duplicates of the same function is indeed bad practice. Your way when you have three users you will have defined function myFunction11 three times. And in fact (as you guessed) you end up with the function only having the last value of city.
Instead, this should be better:
$(document).ready(function() {
$('.team').append(`<script>
function myFunction11(city) {
alert(city);
}
</script>`);
users.forEach(function(user) {
$('.team').append(`
...
<i class="fa fa-pencil"></i>
...`);
});
define function outside loop and pass user index as parameter
function myFunction11(index) {
var city = users[index].handle;
alert(city);
}
$(document).ready(function() {
users.forEach(function(user,i) {
$('.team').append(`<div class="card">
<figure>
<img src="${user.image}" />
<figcaption>
<h4>${user.name}</h4>
<h5>${user.handle}</h5>
</figcaption>
</figure>
<div class="links">
<i class="fa fa-pencil"></i>
<i class="fa fa-truck"></i>
<i class="fa fa-trash-o"></i>
</div>
<div class="task">
<div>
</div>
</div>
<div class="bottom-links">
<i class="fa fa-pencil"></i> EDIT
<i class="fa fa-truck"></i> TRACK
</div>
</div>`);
});
});

How to extract text from element with attribute style="display:none;

HTML of that part is:
<div class="review-small-text">
<span class="stars-rate">
<span property="starsRating">
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
</span>
</span>
<span property="reviewRating" typeof="Rating" style="display:none;">
<span property="ratingValue">5</span>
<span property="bestRating">5</span>
<span property="worstRating">0</span>
</span>
<span property="itemReviewed" typeof="Service" class="">Liposuction</span> </div>
I'm trying to extract the second span's ratingValue of a particular review using selenium and i tried to extract that value by using this css selector:
'div.review-small-text>span:nth-of-type(2)>span:nth-of-type(1)'
but it is giving me an empty string.
have also tried this one
'div.review-small-text>span:nth-child(2)>span:nth-child(1)'
so I think the problem is not in the css-selector. Display none is creating an issue here.
Is there any possible way to extract that value?
Python source code that i have tried so far is:
from selenium import webdriver
import time
url = "myurlhere"
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3)
all_reviews_listings = driver.find_elements_by_xpath("//div[#id='tab_reviews']/div[#class='provider_all_Reviews']/div[#id='pnlReviews']/div")
for review in all_reviews_listings:
review_rating = review.find_element_by_css_selector('div.review-small-text>span:nth-of-type(2)>span:nth-of-type(1)').text
print("Review Rating: ", review_rating)
Here is the css to get the ratingValue.
Using JavaScript:
review_rating = driver.execute_script("""return document.querySelector(".review-small-text > span[property='reviewRating'] > span[property='ratingValue']").textContent""")
Without JavaScript: Alternatively you can also do this.
driver.find_element_by_css_selector(".review-small-text > span:nth-child(2) > span[property='ratingValue']").get_attribute("textContent")
The ancestor tag is having the attribute style="display:none;, so to extract all the reviewRatings you can use the following solution:
driver.execute_script("arguments[0].removeAttribute('style')", driver.find_element_by_css_selector("div.review-small-text span[property='reviewRating'][typeof='Rating']"))
print([element.text for element in driver.find_elements_css_selector("div.review-small-text span[property='reviewRating'][typeof='Rating'] span")])

Categories

Resources