Mouseover even in javascript wont output - javascript

Oh the splash screen of my new site I wish to have a mouseover event which will change the colour of my logo every time the mouse is moved. Below I have listed the code I have so far, but I cannot get it to display my image.
var images = new Array()
images[0] = 'img/CMbl.png'
images[1] = 'img/CMo.png'
images[2] = 'img/CMg.png'
images[3] = 'img/CMp.png'
images[4] = 'img/CMblu.png'
var p = images.length;
logo = document.getElementById( 'logo' ),
console = document.getElementById( 'console' );
logo.addEventListener('mousemove', changeImage);
function changeImage() {
var rand = Math.round(Math.random()*(p-1));
var image = p[ rand ];
if ( image == logo.src ) {
changeImage();
return false;
}
logo.src = console.innerText = image;
function showImage(){
document.write('<img src="+image[rand]">');
}
}
and my output in html should be (Inside the class 'logo')
<script language="javascript">
showImage()
</script>
I cannot see why it's not working. I am using a similar code to change image on refresh, which still uses math.random() and an array to call the images.

This is the way this should look:
document.write('<img src="' + image[rand] + '">');
(your script is full of mistakes from what I can see. I'll make a quick, working one for you as an example.)
Here is a working example(I think this is what you're going for) Jsfiddle example
As you can see, it comes out to a terrible looking effect, I wouldn't suggest using it.

I've made a JSfiddle which cleans up some of the code, and makes use of jQuery.
http://jsfiddle.net/jackcannon/2EXs5/
var images = [
'http://colorvisiontesting.com/plate%20with%205.jpg',
'http://regentsparkcollege.org.uk/wp-content/uploads/2012/09/test.jpg',
'http://nyquil.org/uploads/IndianHeadTestPattern16x9.png',
'http://25.media.tumblr.com/tumblr_m9p3n1vJmZ1rexr16o1_400.jpg',
'http://www.themoralofthestoryis.com/wp-content/uploads/2013/01/test.gif'
];
$('#logo').mouseover( changeImage );
function changeImage() {
var rand = Math.floor(Math.random() * images.length);
var image = images[ rand ];
if ( image == $('#logo').attr('src') ) {
changeImage();
return false;
}
$('#logo').attr('src', image);
};

Related

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Preloader for loading images

I am currently working on SVG SMIL animation in which I am using some .png and .gif files for easing my animation in IE. For this animation I am trying to get Preloader before animation and its other contents get loaded.
Problem is I am not getting that Preloader working properly. My .html page is getting loaded first and then preloader is starting... In Preloader also, I have used several preloaders available on the web. But they are not helpful for me.
Script and .html files loading time can be counted by domContentLoaded but for images. I dont know how to do that. If someone can suggest me a way that would be great.
here is code of preloader.js, I found on web:
$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below.
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;
//Creating loader holder.
$('<div id="loaderMask"><span>0%</span></div>').css({
position:"fixed",
top:0,
bottom:0,
left:0,
right:0,
background:'#fff'
}).appendTo('body');
//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {
var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
var imgVal = $(this).not('image').attr('xlink:href');
//Getting urls of background images.
if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
bgImg.push(val)
}
//Getting src of images in the document.
if(imgVal !== undefined && img.indexOf(imgVal) === -1){
img.push(imgVal)
}
});
//Merging both bg image array & img src array
var imgArray = bgImg.concat(img);
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){
//Attaching load event
$("<image />").attr("xlink:href", val).bind("load", function () {
console.log('val'+val);
completeImageLoading();
});
//Attaching error event
$("<image />").attr("xlink:href", val).bind("error", function () {
imgError(this);
});
})
//After each successful image load we will create percentage.
function completeImageLoading(){
count++;
percentage = Math.floor(count / imgArray.length * 100);
console.log('percentage:'+percentage);
$('#loaderMask').html('<span>'+percentage + '%'+'</span>');
//When percentage is 100 we will remove loader and display page.
if(percentage == 100){
$('#loaderMask').html('<span>100%</span>')
$('#loaderMask').fadeOut(function(){
$('#loaderMask').remove()
})
}
}
//Error handling - When image fails to load we will remove the mask & shows the page.
function imgError (arg) {
$('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
$('#loaderMask').remove();
})
}
});
A little trick I do to ensure my or external data or images are loaded before I start executing my js code is, I create a div with display:none and fill it with all the tags that I need loaded.
<body>
<span id="loadingText">Loading...</span>
<div style="display:none">
<img src="pathtoimage1">
<img src="pathtoimage2">
<img src="pathtoimage3">
</div>
<script>
window.onload = function(){
//This gets called when all the items in that div has been loaded and cached.
document.getElementById("loadingText").style.display = "none";
}
</script>
</body>
I use this for preloading images for animations.
you can add and remove how many you load as needed.
<script language="javascript">function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
img1.src = "image link here";
img2.src = "image link here";
img3.src = "image link here";
img4.src = "image link here";
img5.src = "image link here";
img6.src = "image link here";
img7.src = "image link here";
img8.src = "image link here";
img9.src = "image link here";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);</script>

JavaScript: set background image with size and no-repeat from random image in folder

I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .

Need to set styling rules to a JavaScript image randomizing script

I am trying to set the background images to be fixed and be stretched to fit the screen. the js that i am using if to switch the backgroud image on every pageload
Head
<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>
Body
<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>
The js itsself works fine to randomize the images but is currently set to 1 image
Simple, change both scripts to:
<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
, 'http://tinyurl.com/nqw2t9b'
, 'http://tinyurl.com/nkogvoq'
// , 'url 4'
]
, image = images[ (Math.random() * images.length)|0 ]
; //end vars
window.onload=function(){
document.body.style.background=
"url('"+image+"') no-repeat center center fixed";
document.body.style.backgroundSize=
"cover"; // width% height% | cover | contain
};
</script>
Nothing more to configure, just add/remove/change urls.
Example fiddle here.
Hope this helps.
inum needs to be set to something other than 1. You can set it to the number of images in the array.
Also, arrays start with index 0, so to be safer, you should index your array accordingly.
<script language="JavaScript">
// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";
...
images[4] = "lastImage.jpg";
// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];
// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
// set inum
var inum = images.length;
var randnum = Math.random();
var randIndex = Math.floor(randnum * inum);
// Ensure you have an array item for every image you are using.
var imageFile;
if (randIndex < images.length) {
imageFile = images[randIndex];
}
...
</script>
In the body
<script type="text/javascript">
window.onload = function() {
if (imageFile) {
var body = document.getElementsByTagName("body")[0];
if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
}
}
</script>

change background img each time by clicking link

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...
Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Categories

Resources