change the background image as you onmousemove on the different images javascript - javascript

function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
m.style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')";
var p = document.getElementById('image');
p.innerHTML = previewPic.alt;
}
function unDo() {
/* In this function you should
1) Update the url for the background image of the div with the id = "image"
back to the orginal-image. You can use the css code to see what that original URL was
2) Change the text of the div with the id = "image"
back to the original text. You can use the html code to see what that original text was
*/
document.getElementById("image").style.backgroundImage = "url('')";
document.getElementById('image').innerHTML = "Hover over an image to display here";
}

I suspect this is homework thus I only give you a partial answer here:
function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
// now how would I fix this string concatenation up? hmmm
m.style.backgroundImage = "url('" + previewPic.whattoplacehere +')";
// comment out as we have this var p = document.getElementById('image');
// change to m from p as we had it already.
m.innerHTML = previewPic.alt;
}
What event do we need? We need two it seems, what is the second one?
var myimage = document.getElementById("myimage");
myimage.addEventListener("mousesomething", function(event) {
var target = event.target,
related = event.relatedTarget;
upDate(what should be here?);
}, false);
Research:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

Use this in JS,
document.getElementById("demo").style.backgroungImage = url(" ") ;
Images in Html are already saved in src so, previewPic.src will be images link.
Don't forget to concatenation ..
like this "url" + "(" + parameters.src + ")" ;

Related

Loop through all images inside links, extract image name from the image path and convert it into a string with jQuery

$("a > img").each(function () {
if ($(this).attr("alt") == undefined || $(this).attr("alt") == "") {
var name = $(this).attr('src');
name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to get all images inside a link that don't have an ALT tag. Then get the image name as a string and add it as ALT tag to the image. Everything works fine except for the regular expression. Right now it's adding the image path as an ALT which doesn't fix my ADA issues.
The reason i am doing that is because i am trying to fix the ADA issues on the website. (Every image inside a link must have an alt tag)
You need to reassign the updated value after replace to name variable again and then update the image alt attribute like:
name = name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
// If a link has an image and no aria label
//Get image source, strip everything except for image name
//Add image name as aria-label to the link
$('a:has(> img)').each(function () {
var URL = $(this).children('img').prop('src');
var output = URL.split('/').pop();
output = output.replace(/[- .\s]/g, " ");
$(this).attr('aria-label', output);
});

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

Displaying Images in Javascript

OK, so I'm making a website in HTML, and it's working great, but I need to know how to display images on the page in javascript. I have in my website where there is a part on the homepage called news, and it's going to display an image about the topic, but I don't know how to display the image. When I use other website's ways, the image just displays as a square with a ? in the middle. Please help!!
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.appendChild(content);
I got these answers from:
How to display image with javascript?
How to append data to div using javascript?
This will work:
DEMO
javascript:
var i = document.getElementById('test'); //get the element to put the picture in
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>'; // append the picture to the divs inner HTML
HTML:
<div id="test"></div>
Or without HTML in the first place (of course you need html and body tag...)
DEMO2
Code:
var i = document.createElement('div');
i.id = 'test';
document.getElementsByTagName('body')[0].appendChild(i);
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>';

Show the background image location (http://www...) in textbox HTML JAVASCRIPT

My website allow users to change the background image using a URL with the following code:
var defaultImage = "'#fff'";
document.getElementsByTagName('body')[0].style.backgroundImage = localStorage.getItem('back') ? "url('" + localStorage.getItem('back') + "')" : "url('" + defaultImage + "')";
function changebackground() {
var url = document.getElementById('bgchanger').value;
document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')";
localStorage.setItem('back', url);
}
I was wondering how can the current background image URL be displayed in a textbox?
DEMO: http://goo.gl/253IN
UPDATE:
This is what I would like:
function changebackground() {
var url = document.getElementById('bgchanger').value;
document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')";
// populate the input w/ the url:
document.getElementById('textfield').value = url;
localStorage.setItem('back', url);
}
However every time the page refreshes the textbox is clear. How can I save this information so it always stays in the textbox even when the page is refreshed?
Thank you in advance!
You can get the background image like this:
window.onload = function () {
var bgimage = document.body.style.backgroundImage;
var cleaned = bgimage.replace(/^url\('/, "").replace(/'\)$/, "");
var txtbox = document.getElementById("txt1");
txtbox.value = cleaned || "No background image set";
};
http://jsfiddle.net/KW852/3/
It gets the body's backgroundImage style, then strips any leading url(' and trailing ') and returns the middle text. Then, just sets the textbox's value.
How about:
function changebackground() {
var url = document.getElementById('bgchanger').value;
// populate the input w/ the url:
setBackground(url);
localStorage.setItem('back', url);
}
function setBackground(url){
document.body.style.backgroundImage = "url('" + url + "')";
setText(url);
}
function setText(url){
document.getElementById('textfield').value = url;
}
var defaultImage = "'#fff'";
bgUrl = localStorage.getItem('back') ? localStorage.getItem('back') : defaultImage;
// Set background
setBackground(bgUrl);
The only thing I added was the comment line and the line immediately following it. You already have the URL, it's just a matter of setting the input element's value.
Update
I added some code to initialize the text box when the background is first set (presumably on page load), per your additional requirement in your comment, below.

Categories

Resources