im trying to use html and javascript to create a rotating logo on my site.
I want it to rotate on page load, and load them randomly.
Ive tried SO MANY THINGS! that i found on google, and i cant seem to get it to work. Im trying to avoid using php to do it.
i want to be able to have the random image in a tag like below, (if possible)
<img src="" />
So, just to sum it up.
I want to use "html" and "javascript" to create a script that everytime a page is refreshed, it loads a new logo from a directory on my server.
EDIT: what i have tried
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite(myImage)
</script>
You should avoid using document.write. Instead put an id attribute on the img tag, and retrieve it using document.getElementById. You can make it refresh at intervals using the setInterval method:
<img id="logo" />
<script type="text/javascript">
var logos = ["logo1.png", "logo2.png", "logo3.png"];
var currentLogoIndex = 0;
function updateLogo() {
document.getElementById('logo').src = logos[currentLogoIndex];
currentLogoIndex++;
currentLogoIndex %= logos.length;
}
window.setInterval(updateLogo, 1000);
updateLogo();
</script>
you can store the pathes in an array and select them by using random index.
$(document).ready(function() {
var src = ['path1.jpg', 'path2.jpg', 'path3.jpg', 'path4.jpg', 'path5.jpg', 'path6.jpg', 'path7.jpg', 'path8.jpg', 'path9.jpg'];
$('img').attr('src', src[Math.floor(Math.random()*10)]) // it returns a number between 0 and 10
});
You know, there is a jQuery plugin for this which utilizes CSS transformations.
http://www.zachstronaut.com/posts/2009/08/07/jquery-animate-css-rotate-scale.html
I am Resorting to php guys.
<img src="/images/logo/<?php $random = rand(1,3); echo $random; ?>.png" alt="LOGO!!!!" />
works perfectly :)
<html>
<body>
<h1>Random logo From List</h1>
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite("<img src='" + myImage + "' />)
</script>
<h2>Hoo just got a random logo</h2>
</body>
</html>
Looks like this was what you tried for:
For a bit of explanation using document.write and document.getElement:
When you write inline code like above you can use document.write, it will just add the texts just after </h1> like a normal "print" operation.
Once you use it after document is loaded, it clears everything and overwrites whole thing.
If you want to change the document after it is loaded, you have to edit the DOM, the document is represented as DOM after its loaded. In that case you should use different DOM manipulation functions like
document.getElementById('logo-image').src = myImage;
Related
I have this idea for my website that every time you visit the page, the background will be different. I want to get literally any picture from Google images and place it as my website's background using Javascript.
Basically every time you refresh the page a script will fetch a random picture from Google images and place it as the background or maybe at least download the picture.
How should I do this, or is it even possible?
It can be done via Google Images though much customization is required so the script behaves as you intended (including setting up a delay to handle rate-limiting; Google has a rate-limit of 64 items per search request over API) here is a basic example using Google Images api:
<html>
<head>
<title></title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(OnLoad);
var search;
//i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
var keyword = 'mountains';
function OnLoad()
{
search = new google.search.ImageSearch();
search.setSearchCompleteCallback(this, searchComplete, null);
search.execute(keyword);
}
function searchComplete()
{
if (search.results && search.results.length > 0)
{
var rnd = Math.floor(Math.random() * search.results.length);
//you will probably use jQuery and something like: $('body').css('background-image', "url('" + search.results[rnd]['url'] + "')");
document.body.style.backgroundImage = "url('" + search.results[rnd]['url'] + "')";
}
}
</script>
</head>
<body>
</body>
</html>
However may I suggest instead: Random images from flickr, here is another basic code for that (sky is the limit):
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var keyword = "mountains";
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: keyword,
tagmode: "any",
format: "json"
},
function(data) {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('body').css('background-image', "url('" + image_src + "')");
});
});
</script>
</head>
<body>
</body>
</html>
although not technically what was asked, this could help give some structure to the randomness -- you could compose a couple dictionaries, of verbs, nouns, adjectives.. and mad-lib it up with a random adjective-noun verbing, (ie, fat bulldog running) then query google with that search, and pick a random picture from the results. this way, you can potentially reduce the inappropriate results, and also allow selection of specific dictionaries based on themes the user has selected perhaps. (ie, changing the available nouns based on user's likes)
I'm apparently a bit of a dunce. I've been trying to get this to work as an onload slideshow that will randomly cycle through some images. I've looked through four different questions on here pertaining to how to change the src attribute using javascript and I think that I've avoided all of the problems that have been mentioned on those. The HTML calls the slideShow() function, but for the life of me I can't actually get the src to change and display on the page. Can someone please help me figure out what I've done wrong?
<script><!--
function slideShow()
{
window.setInterval("changeImage()", 5000);
}
function changeImage()
{
var imgSrcs["images//traps//1.jpg",
"images//traps//2.jpg",
"images//traps//3.jpg",
"images//traps//4.jpg"]
var i = Math.floor((Math.random() * 3));
var element = document.getElementById("slideShow").src;
element.innerHTML.src= imgSrcs[i];
}
--></script>
The HTML element that goes with this is:
<p><img src = "images//traps//1.jpg" alt = "Traps available for use" id = "slideShow"></p>
replace the following lines
var element = document.getElementById("slideShow").src;
element.innerHTML.src= imgSrcs[i];
with
var element = document.getElementById("slideShow");
element.src= imgSrcs[i];
I've assumed that slideShow refers to img tag id.
Maybe some of you have already some experience with using head.js.
I'm a first-time user and I'm having some problems: as soon as I try to load multiple javascript files my <html> tag get a style="margin-left: -32767px;" applied.
<script type="text/javascript">
var path = "<?php bloginfo('template_directory'); ?>";
head.js( path + "/js/jquery-1.5.min.js", path + "/js/css3-mediaqueries.js",
path + "/js/jquery-cookie.js", path + "/js/scripts.js", function() { });
</script>
Any idea why that happens? When I get rid of that weird style attribute in my html with Firebug all javascript libraries work just fine. However when the page loads the content flickers and as soon as this negative margin gets applied absolutely nothing is visible on my page.
The negative margin is coming from css3-mediaqueries.js
the code is:
var _57 = document.documentElement;
_57.style.marginLeft = "-32767px";
setTimeout(function () {
_57.style.marginTop = "";
}, 20000);
I don't know what purpose this has but you could probably delete this without a problem, if you don't want to do that then I would apply a style on the html tag
style="margin-left:0 !important;"
or with JS:
document.getElementsByTagName("HTML")[0].style.margin = "0"
I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.
<html>
<head>
<script type="text/javascript">
function SetTimer()
{
var Timer = setInterval("showImage()",3000);
}
function showImage()
{
document.getElementById('showImage').style.visibility = 'visible';
}
</script>
</head>
<body onLoad="SetTimer()" style="visibility:hidden">
<div id=showImage>
<img src="gwyneth_paltrow_2.jpg">
</div>
</body>
</html>
Am I approaching this incorrectly?
thanks in advance
This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';
getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it. Instead, you should start out as hidden, and then make it appear instead of disappear.
document.getElementById('showImage').style.visibility = 'hidden';
Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
var myImage = new Image();
myImage.src = "gwyneth_paltrow_2.jpg";
document.getElementById("showImage").appendChild(myImage);
}
I'm doing that from memory, so syntax may not be entirely correct.
This might be a simple one for you guys, im learning Javascript and have hit a problem. I am trying to have the script resize a particular image on the page when onload is called like so:
<script type="text/javascript">
function resizeSampleImage()
{
document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.2;
}
</script>
...
<body onload = "resizeSampleImage();" >
...
<img id="sampleImage" src="Images/BP snip.jpg" alt="BuildingPeople.uk.com" />
apologies, forgot to mention that is doesn't work! after loading the page in multiple browsers the image stays it native size and the error consoles say they fail to parsing value for height. Declaration dropped.
I have tried lots of different ways but cannot seem to get it to work.
(document.body.clientWidth) * 0.2 will give you an integer. The CSS height property accepts a length.
Add some units.
There is a live example at http://jsbin.com/uyihe4
You can see the zoom effect when loading. I have only changed the
document.getElementById("sampleImage").style.height
to
document.getElementById("sampleImage").height
Well, your problem is that the images may not be ready when you apply the styles to them.
Use this function instead (note it takes a DOM object):
var imgLoader = function(domImg) {
var imgObj = new Image();
imgObj.onload = function()
{
// apply styles
domImg.style.height = "100px";
}
imgObj.src = domImg.src;
}
Though I haven't figure out the problem. But the following code snippet works for me (Tested in Chrome 8.0 and IE9.0Beta).
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeSampleImage()
{
document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.5;
}
</script>
</head>
<body onload="resizeSampleImage();">
<img id="sampleImage" src="http://news.mydrivers.com/Img/20101217/S03405153.jpg">
</body>
</html>