I'm new to this site and relatively new to web development. I was trying to incorporate javascript to this webpage I made with just HTML & CSS. This webpage is basically an online store for certain products and what I was trying to do was that when someone has their mouse over one of the products, it would provide some details such as the name of the product and the price and when they move the mouse out, it would go back to just an image of the product. For some reason, with my code, it will change the elements so that it shows the details but it won't change back to the original image after the mouse moves away.
I've tried everything I could think of and the goal of this project was to make sure I had an understanding of javascript so I was trying to do this without any jquery. Any advice would be greatly appreciated.
Here is the code:
//Holds all div elements with class attribute "productlink" which hold the product images
var products = document.getElementsByClassName("productlink");
//When this function is called, the product image is changed to show an image of the product, the name and price
//classNum - specifc class element being called
//priceAmount - price of product
//describe - Description/Name of the product
function hoverDetails(classNum, priceAmount, describe) {
//Div container for details, image of product, price of product and description
var divContainer = document.createElement("div");
var image = document.createElement("img");
var price = document.createElement("p");
var description = document.createElement("p");
var priceTextNode = document.createTextNode(priceAmount);
var descriptionTextNode = document.createTextNode(describe);
description.appendChild(descriptionTextNode);
price.appendChild(priceTextNode);
image.src = picArray[classNum];
divContainer.setAttribute("class", "newdiv");
image.setAttribute("class", "newimg");
price.setAttribute("class", "itemprice")
description.setAttribute("class", "itemdescription");
products[classNum].parentNode.style.textDecoration = "none";
divContainer.appendChild(image);
divContainer.appendChild(description);
divContainer.appendChild(price);
//This should replace the current image with the details specified eariler
//childNode is set to 1 due to a #text node in the div
products[classNum].replaceChild(divContainer, products[classNum].childNodes[1]);
}
//This function, when called, replaces the detailed product with just an image of the product
function originalImage(classNum) {
var image = document.createElement("img");
image.setAttribute("class", "display_image");
image.src = picArray[classNum];
products[classNum].replaceChild(image, products[classNum].childNodes[1]);
}
Here is the element that is referencing these functions:
<a href="#">
<div class="productlink" onmouseover="hoverDetails(0,'$85.95','Printer') "onmouseout="originalImage(0)">
<img class="display_image" src="images/printer1.jpg" />
</div>
Don't the mind the variable names and I'm sorry if my code seems too much. Any help would be appreciated.
EDIT: Just to let people know, both functions work. The onmouseleave event works when the onmouseover event is not attached. Additionally, the code works when the onmouseover event is replaced with onclick. When I replace onmouseover with onmouseenter, the code works once but never again. This is very strange.
There is actually another mouse event called onmouseout. Add another attribute called onmouseout="removeHoverDetails()" and then inside of removeHoverDetails() select everything and say .visibility = "hidden"; Or whatever way you want to use to get rid of the elements in the popup. Also check out w3schools tutorial on onmouseover and onmouseout: http://www.w3schools.com/jsref/event_onmouseover.asp
Okay I found the solution to my problem. I put the onmouseover event on the image element of the "productlink" div an left the onmouseout event on the div and looks to be working fine.
Related
I'm testing out some jQuery and want to update a image when hovering over a specific div or link block.
So what i was trying to do is when hovering over .test-block get the hidden text with the url and update it on .large-image-2. It can't seem to get the specific text on hover.
This is the code i have come up with:
$('.test-block').on('onmouseenter', function() {
let myUrl = $(this).find('.display-hidden').text();
$('.url').text(myUrl);
});
Im testing on this page: https://jquery-testing.webflow.io/update-image the three bottom div's and bottom picture on right is what i want to use.
Thanks in advance!
There are a few issues with your example. Mainly the way you register the event handler.
For jQuery the correct way would be $(target).on('mouseenter') - Ommit the on... part for the event you want to register when doing it through jQuery.
I would probably implement the functionality you're looking for in a less specific way and with simpler handles like the following:
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this)
const target = that.data('image-target')
const url = that.data('image-url')
$(target).attr('src', url);
})
divs.first().trigger('mouseenter')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=one">
Hover One
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=two">
Hover Two
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=three">
Hover Three
</div>
<img id="my-target-image">
Explanation:
Data attributes:
Two data attributes are getting used in my example: data-image-target and data-image-url.
Using data attributes on the elements you want the event to be fired on will make your script a bit more robust and less prone to errors, since the event registration is bound to the two attributes being present using attribute selectors for the jQuery selector $([data-image-target][data-image-url]) instead of arbitrary classnames and/or ids.
The data-image-target should have a CSS selector that points to the <img> element(s) you wish to switch the src url on, while the data-image-url should hold the url of the image you want to switch to.
The code above could even replace your existing functionality for the top 3 images on your page.
This code worked
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this);
const target = that.data('image-target');
const url = that.data('image-url');
$(target).attr('src', url);
});
});
Thanks to Morten for providing. With Webflow i also had to do Command + Shift + O to turn off responsiveness to the image. (when on image settings)
Attributes:
Name: data-image-target
Value: #my-target-image
And
Name: data-image-url
Value: (image url, in my case Webflow: https://uploads-ssl.webflow.com/something)
These two attributes to each hover element.
Name: id
Value: my-target-image
This to the image element to show images. (if Webflow; "my-target-image" goes in the ID field in element settings.
i am creating a black jack game, and im trying to have the suit appear next to the card that is drawn. However the suit is only showing on the last card drawn, but i want it to be shown after every card thats drawn.
const drawCard = () => {
getCardValue() //returns value from ace-k
getCardSuit() //return heart, spade etc. and sets the corresponding src to img
let cardSpan = document.createElement('span');
cardSpan.innerHTML = ` ${cardNumber} ${cardSuit} `
cardSpan.appendChild(img)
playerHand.append(cardSpan)
}
(im using helper functions to get the card number and card suit). The above code is creating a new span for every card, but like i said only the last card is appending the image. when i console.log it in dev tools i get this
<span>3 clubs</span>
<span>
5 Hearts
<img src... etc>
</span>
any body know how i can get it to appear next to every card? thank you.
Sounds like you only have one image, which is already appended somewhere else, so it moves to the other span. How about:
const image = document.createElement('image')
image.src = ???
cardSpan.appendChild(image)
I have a Chrome extension that inserts a button onto HTML pages. I got it to add the button under one div. Now I'm trying to get it to add it under an image in that div, and it won't work — no errors, the button just doesn't appear. When I do console.log(image_div); it prints out the image object.
Version that works:
var uCW = jNode.closest("[role='article']");
uCW.append(button);
Version that doesn't work:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.append(button);
uCW is the variable name I gave to the parent div, and image_div is the variable name I gave to the child within uCW that contains the image.
The problem that you are having is you are appending to a div successfully, but appending to an image is failing. The reason is you can't append to an image, you have to use 'after' since an image isn't an object that can content appended to the innerHTML of it.
So change this:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.append(button);
to:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.after(button);
I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");
I'm trying to hack together a video player to play local files in a cool interface, it's literally only ever going to be used by my family so the code doesn't have to be beautiful or anything. I've basically got a table full of DVD covers, and when clicked each one of them is supposed to open a modal with a video player for Chrome.
I've managed to do all of this, except I'm struggling to get it so the same button/image can be pressed and a different video file gets shown. Basically this is what I've got inside every table cell:
<th>
<div class="imageBox">
<div class="imageInn">
<img id="standardDVD" src="images/dvdCover1.jpg" alt="Snow">
<div class="hoverImg">
<img id="buttonPlay" src="images/play.png" alt="play">
</div>
</div>
</div>
</th>
I've then got the following JavaScript code to show the modal when that's clicked (I basically took it from here and modified it to show a video instead):
var playButton = document.getElementById('buttonPlay');
playButton.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
var dvdCover = document.getElementById('standardDVD');
dvdCover.onclick = function(){
modal.style.display = "block";
document.getElementById("videoModal").src = videoToPlay;
}
(I've got two basically identical ones so it works if either the DVD cover or the button is clicked)
My thinking was to try and somehow get the src of the image (which should be doable if it's the image that's clicked, but I'm not too sure about how to get the dvd cover src if the button is the one getting clicked. From there I was thinking of having a simple (but long) JavaScript if function to convert each DVD cover to the src of the right video file, and simply change the videoToPlay variable used in the modal:
var videoToPlay = "movies/a Movie.mp4";
Edit since I don't think I was clear: I have a table with 55 different DVD covers, each in one cell and each with the identical HTML code except with a different dvdCover1.jpg image. What I'm trying to do is get it so each one plays the correct video, without having to make a new function for each.
I realize this is definitely not best practice, and any suggestions to improve the overall setup are appreciated - although I'm trying to get this together for Christmas and my knowledge of HTML and CSS is basically zero which is why I'm currently going for simplicity: only 5 people will ever see this anyway so best practice isn't necessarily important!
One option is to create an array with all your movies paths:
var videosToPlay = [
"movies/a Movie.mp4",
"movies/movie a.mp4",
"movies/a new Movie.mp4"
];
Then you need to get all handlers like this:
var dvdsCover = document.getElementsByClassName('standard-dvd-class-in-all-table');
Then just define the click event to all of them using the matching index. Your array must match the full table order of DVDs:
[...dvdsCover].forEach((dvdCover, index) => {
dvdCover.onclick = () => {
modal.style.display = "block";
document.getElementById("videoModal").src = videosToPlay[index];
};
});
Hope it helps.