Java Script Mousovers - javascript

I am implementing a mouseover, which changes the background of a div onMouseDown, and onMouseUp, I am also trying to preload the images.
This is what I have so far;
if(document.images) {
buttonDown = new Image();
buttonDown.src = "buttonDown.png";
}
function down(affect) {
affect.style.backgroundColor="#333333";
affect.style.color="#ffffff";
affect.style.background = buttonDown;
return true;
}
the div uses onMouseDown="down(this);"
This doesn't work. The only part that doesn't work is -- affect.style.background = buttonDown;
I left out the script tags, but they are all there and work as they should.
My question is how do I assign the background property to a preloaded image verses just using a string to assign the image by name.

First, I think you are accessing the wrong style attribute; If you are going to use backgroundColor, may as well go with the more specific backgroundImage.
Second, it requires a string, not an Image Object.
Try this:
affect.style.backgroundImage='url(' + buttonDown.src + ')';
All that said, I would look into image Sprites and HTML classes (CSS) =)

I did some more research and this is what I found. You can preload the images by using a div which is set to style="display:none" and within that div include the images.
As long as the next time you refer to the image, you use the same path it will be preloaded.

Related

What Javascript if/else statement can return an enlarged image to its default size?

I am new to this website and to coding in general. I am having trouble attempting to get an image to shrink back to its "small" size after being enlarged by a single click.
This is my HTML element:
<img src="http://image.com/123.jpg"
id="smart_thumbnail"
class="small"
This id and class cannot be changed, as it is for an assignment. The "small" class automatically turns the image into a thumbnail. It enlarges upon clicking, but I cannot get it to return to its "small" state by clicking it again. It must be done with an if/else statement.
Here is the Javascript template given:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "";
});
});
The double quotes is the "enlarge" class.
Thank you, and I apologize if this post does not fit the format required on this site. I also searched everywhere for this solution but could not find it for the life of me.
This can be done using the DOM classList attribute:
thumbnailElement.classList.toggle("small");
This will remove the small class from the element if it is present, otherwise it will add it.

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML looks like
<div id = "image">
Hover over an image below to display here.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()">
That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
var div_element = document.getElementById('image').innerHTML;
var picurl = "url(previewPic.getAttribute('src'))"
div_element.style.backgroundImage = "url(picurl)";
}
And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
There are multiple issues with your code.
Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.
Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
var div_element = document.getElementById('image');
var picurl = "url(" + previewPic.getAttribute('src') +")"
div_element.style.backgroundImage = picurl;
}
This should work.
If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){
$('div').css(''background-image:'url("image_link")');
});

Change img src on click in list

I'm trying to make an image which changes based on clicking on images in a list.
The only trouble is, the images in the list have their url embedded in a style as a background-image.
How would I call the url of the img src to the new image?
<ul id="swatchList_att1"><li class="Name AttributeSwatch In_stock colourSwatch" id="attributeSwatch_1" data-attname="att1" data-attvalue="Deep Blue (001)" data-atrsku="0012345" style="background-image: url(https://color.adobe.com/api/v2/themes/2022184.png);">
EDIT
Wow, great response time.
and
Wow, I phrased this incredibly poorly yesterday. Apologies.
The list "swatchList_att1" is a group of color swatches which are shrunk to 50% of the jpeg size.
All I'm trying to do is create a sort of "Preview" image which sits in a different div and will show a selected color swatch at an inflated size (110%). On page load, it would be the first color in the list. When a click occurs on a color in the group of color swatches, the "Preview" image would change to what color was clicked.
I can't make changes to how these list items work (i.e. change it to "data-background") because the functionality behind the scenes would break. Annoyingly, I can't do much about that. These list objects need to have their image defined in "style", for whatever reason (I don't know). I can, however, add an onclick function to the list (if I had something that could apply it to all items in the list, which all have very long and different names).
Thus I need to extrapolate the url from the "style" onclick and have "Preview" img src change to that url.
In response to BearSkyView:
Since it's a seperate image, this isn't exactly what I meant. Also, I'd need something which applied an onclick to everything in the list.
In response to somethinghere:
That is more closely along the lines of what I'd like to accomplish, but as I can't change the way these list objects are made, this sadly won't work for me.
http://api.jquery.com/css/
$('#attributeSwatch_1').css("background-image", new src here);
EDIT: Are you looking for something like this? http://jsfiddle.net/rsqtL805/
Since you are using data-attributes anyway, why don't you put it into one? Say data-background="URL".
<img src="" id="myImageElement" alt="large image" />
<img src="path/to/image.jpg" data-background="path/to/image.jpg" onclick="setImg(this); return false;" alt="thumbnail" />
function setImg(obj){
var img = obj.getAttribute('data-background');
document.getElementById("myImageElement").attribute("src", img);
}
Otherwise you can read the background image property and split it in javascript to retrieve the URL and do with it as you like:
var img = this.style.backgroundImage;
img = img.split("rl(")[1].split(")")[0];
The above will take the following string:
url(path/to/image.jpg);
And split it first into:
[0] => u
[1] => path/to/image.jpg)
And then we split the element at place 1 at the ) and select the remainder at index 0.
[0] => path/to/image.jpg
[1] =>
With that you could do
document.getElementById("myImageElement").attribute("src", img);
to set the src of the image element to the just retrieved source.

Java Script - Loading image into a property

I am using the Snowstorm.js javascript file with my webpage.
Current the source allows you to change the character which a 'snowflake' is displayed as. However, I would like to be able change the property of he snowflake to be the image of a snowflake which I have created.
You are able to edit the source and this is the line which sets the character to be displayed.
this.snowCharacter = '•'; // • = bullet, · is square on some systems etc.
Is there any way I can change this to display an image instead of a character and if so, how is this done? I have never worked with Javascript before so for any help or pointers I would be very greatful.
It looks like Snowstorm.js might have the functionality to do this already. Have you seen the information posted at http://www.bozo.us/Javascript/snowstorm/? This page suggests:
File Structure
The script looks for snow images under ./image/snow/ by
default as shown below. If desired, this can be changed in the
user-configurable section.
This seems to correspond to an update mentioned at the bottom of the page you linked, where it says:
1.2.20041121a
Script moved into one file (snowstorm.js) for simplicity
addEventHandler and PNG support functions updated
There's probably a ton of hacky ways to do this in JavaScript, but maybe this will lead you to a clean solution. Good luck!
Find these lines
this.o = document.createElement('div');
this.o.innerHTML = storm.snowCharacter;
this.o.style.color = storm.snowColor;
this.o.style.position = (fixedForEverything?'fixed':'absolute');
this.o.style.width = storm.flakeWidth+'px';
this.o.style.height = storm.flakeHeight+'px';
this.o.style.fontFamily = 'arial,verdana';
this.o.style.cursor = 'default';
this.o.style.overflow = 'hidden';
this.o.style.fontWeight = 'normal';
this.o.style.zIndex = storm.zIndex;
The "o" here is your div element. You can add it a class by adding this line:
this.o.className = "myClass";
To remove the character remove this line:
this.o.innerHTML = storm.snowCharacter;
Than you can style the snowflake with css, the way you know it. Just give it a background image. You can also remove the lines that set the color, width and height and style them with css.
Use unicode '❄' instead of '•' in the original line like this:
this.snowCharacter = '❄';
this will output the snowflake '❄' character as above instead of bullet point.
you might also have to increase these values to 16 or so:
this.flakeWidth = 8;
this.flakeHeight = 8;

How to set a fallback image for img setAttribute

I have an img element:
var photo = document.createElement("img");
which is feed by photos with name stored in an array of objects, so I "feed" the photos like this:
photo.setAttribute('src', './pics/' + myarray[id].Name + '.jpg');
And it works perfect.
The only thing not working is to set an attribute with a default photo for the element that don't have a pic.
I have tried to do a setAttribute line above that one, setting a "default" picture for all the elements, hoping that the second line would replace with proper picture the elements that have one, and leave the default ones untouched, but no... console.log still showed a message of expecting a name+jpg scheme, it totally ignored my previous line (so I am pretty sure is not how it works).
So if you have an img element with many instances through an array, what is the best way to assign a default picture to the elements whose picture is not specified in purpose?
Thanks!
Can you use jQuery. This is a solution for the problem you described. If an image comes back as a 404 then it gets the default image applied
http://jsfiddle.net/gunderson/D3DSt/
var photo = document.createElement("img");
photo.setAttribute("id", "myPhoto");
$('body').append(photo);
$("#myPhoto").attr("src", 'alogo3w.png').error(function() {
$(this).attr("src", "https://www.google.com/images/srpr/logo3w.png");
})
​
Just set only the default if neccessary
photo.setAttribute('src', './pics/' + ( myarray[id].Name ? myarray[id].Name : 'default' ) + '.jpg');

Categories

Resources