I have a little trouble with a JavaScript piece of code.
The code is as it follows:`
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('#profile').css('background-image', 'url(' + backgroundImage + ')');
}
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
`
And my problem is the following, as I don't have almost any knowledge in JavaScript I'm having a hard time figuring out how to clone that code.
I have 2 <div>'s - one with id="profile" and the other with id="start-menu", I want the users of my web page to be able to change the background image of both <div>'s but untill now I have only been able to change the <div> with the id="profile". And the way that they change those backgrounds is through an input button, more exactly this one:
<input id="test" type="file" onchange="loadImageFile(this)" />
I have already tried adding some other characters to some of the functions names, and then just change id="test2" or onchange="loadImageFile2(this), but untill now I haven't been successful.
By the way, I should mention that I don't want the backgrounds to be changed with the same button, there are 2 diffrent input buttons, both with the same structure as above (except for the function calling they are almost the same).
What exactly do I need to change at the JS code above in order for it to work with both div's? Please be at your clearest when writing an answer, as my primar language is not english and sometimes I understand certaint phrases a bit harder.
This line is the important one:
$('#profile').css('background-image', 'url(' + backgroundImage + ')');
See the #profile part? That is a selector. That is telling the browser to change the background for the div with ID=profile. If you changed that to this:
$('#start-menu').css('background-image', 'url(' + backgroundImage + ')');
Then it would update the other div.
If you want it to update the two divs with the same images just do this:
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('#profile').css('background-image', 'url(' + backgroundImage +')');
$('#start-menu').css('background-image', 'url(' + backgroundImage +')');
}
}
If you wanted them to be separate images then you'd have to amend the switchBackground function to accept a parameter for which div to switch.
Related
Psuedo Code:
if currentCondition is snow {
aFunction()
} else {
// something else
}
function aFunction {
look inside the snow folder at /images/condition/snow
chose random jpeg/jpg from that folder
use JQuery to set the css background-image property of a div
}
How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.
EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)
Here's how to pick a random image, provided the number of images is set:
var totalBGs = 15;
var rnd = Math.floor(Math.random() * totalBGs) + 1; // 1 - 15
Next you need to set that as CSS background (jQuery):
$(document).ready(function () {
$("#some_element").css({ backgroundImage: "url(path/to/img/file_" + rnd + ".jpg)" });
});
This example shows you that, if you have image in 'images/' directory with all the images named as image_0.jpg, image_1.jpg, image_2.jpg incrementing ...
change the image file name structure according to your requirement. (Javascript directly cannot search file in server directory, as this might be helpful)
<img src="" align="middle" border="0" name="RandomImg" >
<script language="JavaScript">
// Genarate random value from 0-5, change 6 to any number you want
var rand_no = Math.floor(6*Math.random());
// This defines the source of the preview image (For example images/image_0.jpg)
document.images['RandomImg'].src="images/image_" + rand_no + ".jpg";
</script>
I have a code that works perfectly when the number of thumbnails to rotate is 16 and the location is the same for all (only changes the name of the file due to the thumbnail number). Example: http: //www.urltoimage1.jpg....http: //www.urltoimage16.jpg
This is the html:
<img width="189" height="142" src="http: //www.urltoimage8.jpg" class="someclass" id="latest-499" onmouseover="thumbStart('latest-499', 16, 'http: //www.urltoimage');" onmouseout="thumbStop('latest-499','http: //www.urltoimage8.jpg');">
Here is the javascript:
// JavaScript Document
//rotating thumb functions
var rotateThumbs = new Array();
function changeThumb( index, i, num_thumbs, path)
{
if (rotateThumbs[index])
{
if(i<=num_thumbs){
document.getElementById(index).src = path + i + ".jpg";
i++;
setTimeout("changeThumb('"+ index +"'," + i + ", " + num_thumbs + ", '" + path + "')", 600);
}else{
changeThumb( index, 1, num_thumbs, path);
}
}
}
function thumbStart(index, num_thumbs, path)
{
rotateThumbs[index] = true;
changeThumb( index, 1, num_thumbs, path);
}
function thumbStop(index, srco)
{
rotateThumbs[index] = false;
document.getElementById(index).src = srco;
}
Now, the problem is for some articles the thumbnails are not in the same location. Example: http: //www.urltoimage1.jpg....http: //www.urltoimageksks16.jpg
I think that, in the existence of this discrepancy, it is better to copy all the urls of the thumbnails to the class of the image, leaving the html in this way:
<img width="189" height="142" src="http: //www.urltoimage8.jpg" class="http: //www.urltoimage1.jpg,http: //www.urltoimage2.jpg,...,http: //www.urltoimageksks16.jpg" id="latest-499" onmouseover="thumbStart" onmouseout="thumbStop('latest-499','http: //www.urltoimage8.jpg');">
Now that I have all the urls in the class of the img tag, how can achieve that the thumbnail rotate?
Thanks
don't store the urls in the class attributes, use Data Attributes instead. (or Data Attributes from jQuery)
something like
<img .. data-thumbnail-url="http: //www.urltoimageksks16.jpg" .. />
if you're using jQuery (you've added it to your tags), you could use directly
var thumbnailSrc = jQuery('img').data('thumbnail');
if you're not using it (since I don't see any jQuery at all in your code) you have to use this instead
var thumbnailSrc = document.getElementById(index).dataset.thumbnail
using that, you could replace your src attribute. you'll probably want to store in data attributes the original src.
About rotating itself (It is not clear if it is part of your question or if you want to know if it is ok to store the urls in class attributes), there are answers for that using jquery, like jQuery animate image rotation You only need to adapt the functionality to be executed on hovering. You could use pure css as well Spin or rotate an image on hover
On a side note, use this
var rotateThumbs = [];
rather than
var rotateThumbs = new Array();
See In JavaScript, why is [ ] preferred over new Array();?
I have the following HTML in my project.
<div class="container" id="crop">
<img id="timage" src="http://example.com/color/style/etc/" alt="timages" />
I also have the following javascript:
$(window).load(function () {
$("#slider").change(function update() {
sVal = $(this).val();
if (sVal == 2) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
sVal = $(this).val();
if (sVal == 3) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
);}
It works splendidly to replace the image with the string when the slider value reaches certain numbers. The problem is, the image is being created on the back end behind the scenes and takes quite some time before it is ready. In the meantime, you are just staring at the original image wondering if the slider did anything.
How do I add a loading indicator to let people know that the image is about to change?
First, place a loading indicator where you want it. You could replace #timage with a spinning gif, for example. Then use this code to start the new image loading:
var img = new Image();
img.onload = function () {
$('#timage').prop('src', img.src);
}
img.src = '/image/to/load/here';
The function will be executed when your new image has been retrieved from the server and loaded. Since it's already cached on the client, it should load instantly once the src for #timage is set.
Here I use two images. when i click once on the Sort_down.png image then it changes to Sort_up.png.
When I click on this image again it is not changing back to Sort_down.png, how can I achieve this ?
<script type="text/javascript">
function clkimg() {
var img = document.getElementById('stCodeDSC');
img.src = '../Images/sort_up.png';
}
</script>
<td width="11%" bgcolor="#C5DEFF" class="menu_header">
<div align="center" onclick="clkimg();" >
<img name="stCodeDSC" class="img" src="../Images/Sort_down.png" id="stCodeDSC">
</div>
</td>
Depending on the browser you're using, when the source of an image is set to a relative URL, reading it back will give you the absolute URL. If you want to use a toggle, you can check for a string in the source, for example:
function clkimg() {
var img = document.getElementById('stCodeDSC'),
nextImg = img.src.indexOf('up.png')>0 ? 'down':'up';
img.src = '../Images/sort_' + nextImg + '.png';
}
If the sort_up and sort_down images are actually icons just identifying the up or down state of the current sort, you can combine the two images into one and use them as a sprite that you display using CSS. More details will be available at https://stackoverflow.com/search?q=css+sprite
You aren't telling it to sort down. In your click code you'll need to test if the image is showing up or down and change it accordingly. Something like:
if(img.src === '../Images/sort_up.png')
img.src = '../Images/sort_down.png';
else
img.src = '../Images/sort_up.png';
Generally, however, this would be better handled by adding or removing a class on click and styling the class using css.
I have, what I think is, a strange issue. I am running a simple query that finds the largest image on a page. Here is some test data - all images are 32x32 but one is sized to 300x300.
<img src="app/assets/images/icons/blue.png" />
<img src="app/assets/images/icons/error.png"/>
<img src="app/assets/images/icons/info.png" height="300" width="300"/>
If I run a simple query like this:
$('img').each(function(){
console.log($(this).height());
});
I will get 0,0,300 — and not 32,32,300.
Can anyone point me to a better method of finding the size the image is being rendered at?
Thanks.
If the image is "natively" sized, i.e. no width or height are present in the HTML, you'll need to wait for the image to load before you know its size. I use this:
jQuery("img").each(function(){
var img = jQuery(this);
if (img.attr("complete")) {
console.log(img.height());
} else {
img.load(function(){
console.log(img.height());
});
}
});
Make sure you do it after the image is ready in $(img).load(), then it will work. Try JavaScript to verify:
function iLoad(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);