JavaScript - Draggable Background Image
I am trying to recreate this functionality on my website where you can drag a background image around and when you get ot the edges of the image it bounces back to the edge of that corrosponding side. have a look at the site in question - http://irrland.sonntagskunst.de/#
so far i have recreated the top left and right edges using Code: var window_width = $(window).width(); var window_height = $(document).height(); var image_height = $("#background").height(); (2914px) var image_width = $("#background").width(); (3920px) $("#background").draggable({ scroll: false, stop: function (event, ui) { var animate_to = {}; var window_width_resized = $(window).width(); if (ui.position.left > 0) { animate_to.left = '0px'; } if (ui.position.top > 0) { animate_to.top = '0px'; } //initial size for width var image_width_gap = window_width - (image_width + ui.position.left); if (image_width_gap > 0) { animate_to.left = (0 - (image_width - window_width)) + 'px'; } //after window gets resized for width var image_width_gap_resized = window_width_resized - (image_width + ui.position.left); if (image_width_gap_resized > 0) { animate_to.left = (0 - (image_width - window_width_resized)) + 'px'; } $("#background").animate(animate_to, { duration: 1000, easing: "easeOutElastic" }); then i am using the same logic to do the bottom edge but it doesnt work any ideas here is how i thought the bottom would work Code: //initial size for height var image_height_gap = window_height - (image_height + ui.position.top); if (image_height_gap > 0) { // animate_to.top = (0 - (image_height - window_height)) + 'px'; } help would be greatly appreciated fixed.. my bg image was infact smaller Similar TutorialsHi everyone, I have some images that I want the user to be able to move around the page. So far, this script in the header allows me to do this: Code: var ie=document.all; var nn6=document.getElementById&&!document.all; var isdrag=false; var x,y; var dobj; function movemouse(e) { if (isdrag) { dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x; dobj.style.top = nn6 ? ty + e.clientY - y : ty + event.clientY - y; return false; } } function selectmouse(e) { var fobj = nn6 ? e.target : event.srcElement; var topelement = nn6 ? "HTML" : "BODY"; while (fobj.tagName != topelement && fobj.className != "dragme") { fobj = nn6 ? fobj.parentNode : fobj.parentElement; } if (fobj.className=="dragme") { isdrag = true; dobj = fobj; tx = parseInt(dobj.style.left+0); ty = parseInt(dobj.style.top+0); x = nn6 ? e.clientX : event.clientX; y = nn6 ? e.clientY : event.clientY; document.onmousemove=movemouse; return false; } } document.onmousedown=selectmouse; document.onmouseup=new Function("isdrag=false"); The body has this: Code: <img src="images/balloons.gif" class="dragme"> Now, to be able to use this image as a link, I would have to find the displacement between the mousedown and mouseup coordinates. If the displacement is below say 10px, then the mouseup would bring them to another page. I also wanted to make it so that if the mouseup occurs in a certain area of the page, that the image would move itself to a certain spot. I've programmed a lot before, but not in JavaScript. Any help would be much appreciated. (Note: I need this done in JavaScript, not Flash, even though it might be easier). Thanks Hi guys I need help on sorting out a drag&drop script I'm a bit of a rookie with programming, so I found this script somewhere and I managed to implement it in my code...unfortunately now I need to slightly modify the code, and I'm completely lost I have this drag&drop script that moves some images around the screen, but I'd like to assign an event document.getElementById("XXXXX").onclick = blablabla to each of those images. The problem is that, of course, every time I click on the image to drag it around, this activates the link. With a doubleclick event everything works smooth, however it's a solution I don't quite like. I was thinking about a way to control the code so that while the image moves the link is somehow "not active", but if the user simply clicks without dragging then it activates the .onclick function I have the following piece of code in the head section of my page, which is the actual code for dragging the elements Code: function Browser() { var ua, s, i; var ln = 1; this.isIE = false; this.isNS = false; this.version = null; ua = navigator.userAgent; s = "MSIE"; if ((i = ua.indexOf(s)) >= 0) { this.isIE = true; this.version = parseFloat(ua.substr(i + s.length)); return; } s = "Netscape6/"; if ((i = ua.indexOf(s)) >= 0) { this.isNS = true; this.version = parseFloat(ua.substr(i + s.length)); return; } // Treat any other "Gecko" browser as NS 6.1. s = "Gecko"; if ((i = ua.indexOf(s)) >= 0) { this.isNS = true; this.version = 6.1; return; } } var browser = new Browser(); // Global object to hold drag information. var dragObj = new Object(); dragObj.zIndex = 0; function dragStart(event, id) { var el; var x, y; // If an element id was given, find it. Otherwise use the element being // clicked on. if (id) dragObj.elNode = document.getElementById(id); else { if (browser.isIE) dragObj.elNode = window.event.srcElement; if (browser.isNS) dragObj.elNode = event.target; // If this is a text node, use its parent element. if (dragObj.elNode.nodeType == 3) dragObj.elNode = dragObj.elNode.parentNode; } // Get cursor position with respect to the page. if (browser.isIE) { x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } if (browser.isNS) { x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } // Save starting positions of cursor and element. dragObj.cursorStartX = x; dragObj.cursorStartY = y; dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10); dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10); if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0; if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0; // Update element's z-index. dragObj.elNode.style.zIndex = ++dragObj.zIndex; // Capture mousemove and mouseup events on the page. if (browser.isIE) { document.attachEvent("onmousemove", dragGo); document.attachEvent("onmouseup", dragStop); window.event.cancelBubble = true; window.event.returnValue = false; } if (browser.isNS) { document.addEventListener("mousemove", dragGo, true); document.addEventListener("mouseup", dragStop, true); event.preventDefault(); } } function dragGo(event) { var x, y; // Get cursor position with respect to the page. if (browser.isIE) { x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } if (browser.isNS) { x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } // Move drag element by the same amount the cursor has moved. dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px"; dragObj.elNode.style.top = (dragObj.elStartTop + y - dragObj.cursorStartY) + "px"; if (browser.isIE) { window.event.cancelBubble = true; window.event.returnValue = false; } if (browser.isNS) event.preventDefault(); } function dragStop(event) { // Stop capturing mousemove and mouseup events. if (browser.isIE) { document.detachEvent("onmousemove", dragGo); document.detachEvent("onmouseup", dragStop); } if (browser.isNS) { document.removeEventListener("mousemove", dragGo, true); document.removeEventListener("mouseup", dragStop, true); } } then in the Body, I have the DIV that can be dragged around through the "onmousedown" event Code: <div id="milano" class="aBar" style="width:auto; height:auto;" onmousedown="dragStart(event, 'milano')"> <?php print '<a href="#"><img border="0" src="images/works/thumbnails/milano.jpg" alt="" style="float:left; position:absolute; top:'.rand(50,300).'px; left:'.rand(100,500).'px"/></a>' ?> </div> then, in the Body as well, I have the javascript that I'd like to activate only if the image is clicked on BUT not dragged around Code: <script> window.onload = function () { document.getElementById("milano").onclick = function () { alert('AAAAA'); } } </script> I'm really sorry the code is REALLY messy, but as I said I'm just a rookie and I know this is not an elegant solution at all Thank you very much for your time, I really hope you can help me out with that as I spent the last 2 weeks tying to find a solution... Cheers, Mattia I am designing a site where users can submit a location. I want to use Google Maps with a draggable marker which posts the lat, lon when dropped on a position. I was wondering if anyone knows of a tutorial or could point me in the direction of anything similar. Hi There I am trying to create some ajax/javascript to append the scriptaculous Draggable to a number of div elements with a className of draggable. The problem is i need to get the id's of each element to make them draggable, as simply making all div elements on the page draggable would effect other elements on the page which I dont want to be so. I need to:- 1.create a collection of div elements with className - draggable 2. make a list of all the element id's 3. make all elements with said id's draggable I have left out the draggable part from the code, I have simply been trying to get the element id's to display so far Code: var dv; var dh; dv = document.getElementsByTagName('div'); if (dv.className == 'draggable') { for (var i = 0; i <= dv.length; i++) { dh = dv[i].getAttribute('id'); for (var j = 0; j <= dh.length;j++) { document.getElementById('content').innerHTML = dh[j].getAttribute('id'); } } } else { alert ("no id"); } I keep getting the alert message "no id" loaded Hi i am trying to create a draggable css layer. Code: <html> <head> <style type="text/css"> #box {position:absolute; left:150;top:150; background-color:blue; height:100; width:100;} </style> <script type="text/javascript"> function start(){ var count = cnt.value var count=0; while (count=0) { var x; var y; var layer = document.getElementById('box'); x=window.event.clientX; layer.style.left=x; y=window.event.clientY; layer.style.top=y; } } function stop(){ var count = cnt.value; count = 1; } function shw(){ alert(cnt.value); } </script> <body> <input type="hidden" name="cnt" value="1"> <div id="box" onclick="start()" onrelease="stop()"> </div> <br /><br /><br /><br /><br /><br /><br /> <input type="button" name="show" value="Show" onclick="shw()"> </body> </html> It doesn't seem to work though. The loop never seems to start. btw i was also thinking couldn't i just put while(box.clicked) { or something along those lines. Thanks I set out to do a little exercise in creating draggable divs that look like app windows in pure javascript, with very little html. Problem is my mouseup event isn't always triggering and will never drop the div in the new spot. I have a global variable to determine whether or not the div is being dragged. This is toggled on the mouseup and mousedown events on the titlebar div. I have a mouesmove event on the body so that it can determine if the global dragging variable is true or false. If true then it moves the div to the x/y coordinates of the mouse Same thing with the mouseup event. It should move the div to the x/y coordinates of the mouse Sometimes it works, sometimes it doesnt. Most of the time it acts like it just wants to select text while I'm dragging (which i thought my selectstart event would take care of) Code: <html> <head> <title>testjs</title> <script> var dragging = false; function Window(title,top,left,width,height) { this.title = (typeof title == 'undefined')?'New Window':title; this.x = (typeof top == 'undefined')?0:top; this.y = (typeof left == 'undefined')?0:left; this.width = (typeof width == 'undefined')?600:width; this.height = (typeof width == 'undefined')?400:height; this.borderStyle = 'solid'; this.windowPanel = null; this.Open = function() { var windowPanel = document.createElement('div'); windowPanel.setAttribute('id','windowPanel'); windowPanel.setAttribute('z-index', '2'); windowPanel.style.position='absolute'; windowPanel.style.left = this.x+'px'; windowPanel.style.top = this.y+'px'; windowPanel.style.width = this.width + 'px'; windowPanel.style.height = this.height + 'px'; windowPanel.style.border = 'thin solid black'; var titleBar = document.createElement('div'); titleBar.setAttribute('id','titleBar'); titleBar.setAttribute('z-index', '4'); titleBar.style.position = 'absolute'; titleBar.style.left = '0px'; titleBar.style.top = '0px'; titleBar.style.width = this.width + 'px'; titleBar.style.height = '22px'; titleBar.style.borderBottom = 'thin solid black'; titleBar.innerHTML = "<span style=position:absolute;>"+this.title+"</span>"; titleBar.addEventListener('mousedown', function(e){MouseDown(e,this)}, false); titleBar.addEventListener('mouseup', function(e){MouseUp(e,this)}, false); titleBar.addEventListener('selectstart', function(e){return false}, false); var closeButton = document.createElement('div'); closeButton.style.position = 'absolute'; closeButton.style.left = this.width - 30 + 'px'; var cbimg = document.createElement('img'); cbimg.setAttribute('src', 'close_button_red.png'); cbimg.setAttribute('width', '16'); cbimg.setAttribute('height', '16'); closeButton.appendChild(cbimg); closeButton.addEventListener('click', function(event){CloseWindow('windowPanel')}, false); document.body.addEventListener('mousemove', Mover, false); titleBar.appendChild(closeButton); windowPanel.appendChild(titleBar); document.body.appendChild(windowPanel); } } function Mover(e) { if(dragging == true) { console.log(e.pageX); document.body.style.cursor = 'move'; document.getElementById('windowPanel').style.x = e.pageX + 'px'; document.getElementById('windowPanel').style.y = e.pageY + 'px'; } else document.body.style.cursor = 'auto'; } function MouseUp(e,ele) { dragging = false; ele.parentNode.style.top = e.pageY + 'px'; ele.parentNode.style.left = e.pageX + 'px'; } function MouseDown(e,ele) { dragging = true; } function CloseWindow(wnd) { document.body.removeChild(document.getElementById(wnd)); } function init() { wnd = new Window('A new approach', 100, 150, 1024, 768); wnd.Open(); } </script> </head> <body onLoad='javascript:init()'> <a href="#" onClick="javascript:init();">Open</a> </body> </html> Hi Guys, I've been searching the net for both examples and pluggins to create draggable divs and although I've found many, I cant find the effect I'm after. I want the div to slow down to a stop after it has been release like when you are scrolling on one of apples mobile devices. If anybody can point me in the right direction ill be very great full. I currently am using a mootools popup on www.Hope1st.com to play his music videos.....and its working really well...only thing is on some computers (mac with firefox browser) when someone pauses the video ...the draggable box gets stuck on their mouse weird right? yea i know... so i thought of a solution...instead of the whole box being draggable why not just the black titlebar be draggable? i have absolutely no idea on how to do this....but i do have the entire JS code....are you ready? its a mouthful....a million thanks to whoever is talented enough to help me Code: var mooSimpleBox = new Class({ options: { width: 300, height: 200, opacity: '0.8', btnTitle: "Ok", closeBtn: null, boxTitle: "messageBox", boxClass: 'mainBox', id: 'myID', fadeSpeed: 500, box: null, addContentID:null, addContent: null, boxTxtColor: '#000', isVisible: false, isDrag: true }, initialize: function(options){ this.isVisible = false; if(options['isDrag']) this.isDrag = options['isDrag']; if(options['width']) this.width = options['width']; if(options['height']) this.height = options['height']; if(options['opacity']) this.opacity = options['opacity']; if(options['btnTitle']) this.btnTitle = options['btnTitle']; if(options['boxTitle']) this.boxTitle = options['boxTitle']; if(options['boxClass']) this.boxClass = options['boxClass']; if(options['boxTxtColor']) this.boxTxtColor = options['boxTxtColor']; if(options['fadeSpeed']) this.fadeSpeed = options['fadeSpeed']; if(options['id']) this.id = options['id']; if(options['closeBtn']) this.closeBtn = $(options['closeBtn']); if(options['addContentID']) this.addContentID = options['addContentID']; if(options['addContentID']) { this.addContent = $(this.addContentID).innerHTML; $(this.addContentID).setStyle('visibility','hidden'); $(this.addContentID).remove(); } this.createBox(); }, createBox: function(){ this.box = new Element('div'); this.box.addClass(this.boxClass); }, clickClose: function(){ $(this.box).effect('opacity',{ wait:true, duration:this.fadeSpeed, transition:Fx.Transitions.linear }).chain(function(){ }).start(this.opacity,0); this.box.setStyle('display','none'); this.isVisible = false; }, fadeOut: function(){ if(this.isVisible){ $(this.box).effect('opacity',{ wait:true, duration:this.fadeSpeed, transition:Fx.Transitions.linear }).chain(function(){ }).start(this.opacity,0); this.isVisible = false; } }, fadeIn: function(){ if (document.documentElement && document.documentElement.clientWidth) { theWidth=document.documentElement.clientWidth; }else if (document.body) { theWidth=document.body.clientWidth; } if (window.innerHeight) { theHeight=window.innerHeight; }else if (document.documentElement && document.documentElement.clientHeight) { theHeight=document.documentElement.clientHeight; }else if (document.body) { theHeight=document.body.clientHeight; } var top = window.getScrollTop(); var boxTop = (theHeight - this.height) / 2 ; boxTop = (boxTop + top); var boxLeft = (theWidth - this.width) / 2; this.box.setStyle('top',boxTop); this.box.setStyle('left',boxLeft); this.box.setStyle('position','absolute'); this.box.setStyle('width',this.width); this.box.setStyle('height',this.height); this.box.setStyle('opacity',this.opacity); this.box.setStyle('cursor','move'); this.box.setStyle('z-index','999990000'); this.box.setAttribute('id', this.id); this.box.setStyle('visibility','hidden'); this.box.injectInside(document.body); if(this.isVisible == false){ this.box.effect('opacity',{ wait:true, duration: this.fadeSpeed, transition: Fx.Transitions.linear }).start(0,this.opacity); this.addHT(); this.isVisible = true; } }, addHT: function(){ this.closeBtn = new Element('button', { styles: { 'border': 'none', 'background-image':'url(modules/mod_moopopup/moopopup/images/bg_button.gif)', 'color':'#fff', 'position':'absolute', 'bottom':'3px', 'right':'3px', 'width':'44px', 'height':'19px', 'font-size':'13px', 'font-weight':'bold', 'font-family':'arial', 'cursor':'pointer' } }) var width = this.width.toInt() + 5; if(window.ie){ var titleBar = new Element('div', { styles: { 'width' : width, 'height': 'auto', 'background-repeat': 'repeat-x', 'background-position': 'right top', 'line-height': '20px', 'padding': '5px 5px 5px 10px', 'position': 'absolute', 'clear': 'both', 'margin-bottom': '10px', 'top': '0px', 'left': '0px', 'color': '#eee' } }) }else{ var titleBar = new Element('div', { styles: { 'width' : width, 'height': 'auto', 'background-repeat': 'repeat-x', 'background-position': 'right top', 'line-height': 'auto', 'padding': '5px 5px 5px 10px', 'position': 'absolute', 'clear': 'both', 'margin-bottom': '10px', 'top': '0px', 'left': '0px', 'color': '#eee' } }) } $(titleBar).innerHTML = this.boxTitle; var insideDiv = new Element('div',{ styles: { 'padding':'10px' } }); insideDiv.setAttribute('id','myContent'); this.box.innerHTML = ""; insideDiv.injectInside(this.box); insideDiv.innerHTML = this.addContent; this.closeBtn.innerHTML = this.btnTitle; $(this.closeBtn).addEvent('click',this.clickClose.bindWithEvent(this)); titleBar.injectInside(this.box); this.closeBtn.injectInside(this.box); if(this.isDrag == 'true'){ this.box.makeDraggable(); } } }); mooSimpleBox.implement(new Options, new Events); Hi, Does anybody know of an example of creating a draggable iFrame in a similar way what can be done on iGoogle with the iFrame gadget using javascript? The problem that I'm having is that the elements within the iFrame can still steal the input focus when dragging the frame using the bar I'm using to initate the drag process. For example when clicking and holding the mouse down on a bar that I'm using to initiate the drag positioned above the iFrame and then moving the mouse to drag the whole frame containing the bar and iFrame I have a problem whereby if the cursor strays over the google search box on http://www.google.com the editbox steals the input focus and the dragging stops until you carefully move the mouse carefully out of the editbox control. Can anybody point me to a page/the html/css containing an iFrame containing http://www.google.com that can't be interacted with because it has a div on top of it e.g. a semitransparent one would look nice for example. Then hopefully I can incoperate the changes into my javascript on initiation of the drag of the frame to disable the elements within the iFrame? If there are any other solutions to this problem, prefereably with an example that works with browsers back as far as ie6 please let me know? Cheers Ben W Hi all, I was wondering if anyone knew were I can get a javascript that will adjust the background image dependant on the users screen resolution like whats used on this site http://gregorywood.co.uk/journal/chilli-babies Thanks in advance!! Kyle I found a great little starfield script made with javascript and canvas3d. however i can't for the life of me figure out how to implement a background image inside the canvas. is there some command that tells it to use some feature of canvas, that if otherwise not called, won't allow normal graphics? his whole starfield is generated with a search engine form , and appears to just use a text period to represent stars. here's a link to his script: http://seb.ly/demos/canvas3d/canvas3d2.html how do i get a background image in that? or is it impossible? i tried putting it in the body tag, but it just flashed the background image on the screen for a half a second and then went back to showing only the black background. i tried removing the background body color and replacing it with only background-image ccs, same problem. i tried div positioning it, but the div just covered up the starfield. Im going nuts with this, first im starting of by just putting a background image in the tb using JavaScript, but it won't work! Heres what i got in my 'name.js' file i got var name=new Array() name='name.jpg' and in my HTML i got <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> </head> <body> <div> <table> <script type="text/javascript" language="JavaScript" src="name.js"> document.write('<td id="name2" background="' + name + '">'); </script> </td> </table> </div> </body> </html> Where have a gone wrong?? If I type Hello World into the name.js file and put it in a tb it works fine, im confused thanks, Paul Hello, I have recently been working on a website which will have rotating background images. I have found a useful javascript code (i don't know who the author is) which rotates different background images neatly after x milliseconds. here is the code: ==== <script language="JavaScript1.2"> var bgimages=new Array() bgimages[0]="../gfx/bgs/bg1.jpg" bgimages[1]="../gfx/bgs/bg2.jpg" //preload images var pathToImg=new Array() for (i=0;i<bgimages.length;i++){ pathToImg[i]=new Image() pathToImg[i].src=bgimages[i] } var inc=-1 function bgSlide(){ if (inc<bgimages.length-1) inc++ else inc=0 document.body.background=pathToImg[inc].src } if (document.all||document.getElementById) window.onload=new Function('setInterval("bgSlide()",6000)') </script> ==== The script works, and the background images rotate. However, currently the rotation of the images have no effect. I would like to add the effect of the images blending into each other when they rotate. How would this be possible? Thanks a bunch! -Captainel How am I able to have a gallery of images fading in and out as the background of a DIV? It's currently just a static background using CSS. You can view the HTML page in question he http://aksdesigns.co.uk/temp/template.html The DIV container is the one with the ID of #MainContent Code: #MainContent { width: 980px; height: 550px; margin: 0 auto; padding: 0px; background-image: url(images/Content-bg-1.jpg); background-repeat: no-repeat; background-position: top center; border-left: 2px solid #153365; border-right: 1px solid #FFF; } It probably couldn't be done using CSS be how could I achieve this with Javascript? Hello, I've just finished my website. But my random background images load properly sometimes, and sometimes they load as a half. Here is my website: http://www.finnhaverkamp.com/ Here is the relevant HTML: Code: <!--open random background script--> <script type="text/javascript"> var randnum = Math.random(); var inum = 7; var rand1 = Math.round(randnum * (inum-1)) + 1; var images = new Array; images[1] = "background1.jpg"; images[2] = "background2.jpg"; images[3] = "background3.jpg"; images[4] = "background4.jpg"; images[5] = "background5.jpg"; images[6] = "background6.jpg"; images[7] = "background7.jpg"; var image = images[rand1]; function chBackgr() { document.body.style.backgroundImage = 'url(' + image + ')'; } onload = chBackgr; <!--close random background script--> It's weird. Because my background image is certainly random. It's just that sometimes only half of the image loads. Really strange. Any help is appreciated. Thank You. Hi Guys, I would like to be able to change my webpage background image according to the screen resolution the user uses so: if screen resolution is greater than or equals to 1200*600 then background = mybackground.jpg no-repeat else background = #000000 THANKS A MILLION! I want to use an image as a CSS background-image so I used the Image constructor to load the image: Code: (new Image()).src="http://www.mediafire.com/imgbnc.php/432b35f2cc3340ea03d25128ada294476c92189353679dfb7e9cc9dfde6498f06g.jpg"; but I noticed that the browser (Firefox) load the image from the URL and not from the memory when changing the background-image property (it takes about 1.5 seconds before showing the image, and every time I reload the page!) I have 3 background images, and 1 is picked at random to be the background image of the body when loading the page.My code is below. Right now it's just white, can't get any pictures to load. I have checked the URLs and they are correct. Can someone help out? Here is my code in the header: Code: <script type="text/javascript"> function getBackground(){ var bgimg = new Array(); bgimg[0] = "background1"; bgimg[1] = "background2"; bgimg[2] = "background3"; var random = Math.floor(Math.random() * bgimg.length); var imgurl = bgimg[random]; document.body.style.backgroundImage = 'url(' + imgurl + ')'; } </script> body: Code: <body onload="getBackground()"> After you click on the last button 3 times it should change the background to the zombies image however it isn't working. I haven't found tutorials for doing it exactly as I am attempting it but I don't see why this isn't working. It runs through the code just fine and the button works as intended except for the fact that the background image isn't changing. I am still pretty new to JavaScript however so I feel I may just being calling the image incorrectly. Code: <html> <title>Welcome :D</title> <head> <style type="text/css"> body { background-color:E6E6E6; } </style> <script type="text/javascript"> //Pre loading images to be used with check boxes. function preLoad(){ Eyeball= new Image(400,200) Eyeball.src = "Eyeball.jpg" Smileys = new Image(400,200) Smileys.src = "Smileys.gif" goodAfternoon = new Image(400,200) goodAfternoon.src = "Good Afternoon.gif" goodAfternoonFinal = new Image(400,200) goodAfternoonFinal.src = "Good Afternoon.gif" zombies=new Image() zombies.src = "Zombies.jpg" } function validate(){ if(document.getElementById("cb1").checked){ document.goodAfternoon.src=Eyeball.src; }else{ document.goodAfternoon.src=Smileys.src; } } function reset(){ cb1.checked=false; document.goodAfternoon.src=goodAfternoonFinal.src; } var i=0; function myalert(){ i++ if(i == 1){ alert("I dare you to press me again...."); } if(i == 2){ } if(i == 3){ i = 0; document.body.background = "zombies.src"; } } </script> </head> <body onLoad="javascript:preLoad()"> This is where I learn a lot of my coding for Java, JavaScript, and HTML <a href="http://www.thenewboston.com/"><img src="theNewBoston.gif"></a> </br> "Check" me out;) <input type="checkbox" id="cb1" onClick="validate()" /> <img src="Good Afternoon.gif" name="goodAfternoon"> <input type="button" id="cb2" value="RESET" onClick="reset()"/> </BR></br></br></br></br> Hello, thank you for visiting my webpage I hope you like it. <input type="button" onClick="myalert()"value="CLICK me"/> </body> </html> Hey, everyone! I found this script that works great for what it's for. However, I would like to use it for background images. Can someone tell me how to adjust this script so it can be used for backgrounds? Thanks in advance! Web Page Code Code: <html> <head> <title>slayeroffice | code | image cross fade redux</title> <link rel="stylesheet" type="text/css" href="xfade2_o.css"> <script type="text/javascript" src="xfade2.js"></script> </head> </div> <body background="id=imageContainer"> <div id="imageContainer"> <img src="http://slayeroffice.com/code/imageCrossFade/img1.jpg"> <img src="http://slayeroffice.com/code/imageCrossFade/img2.jpg"> <img src="http://slayeroffice.com/code/imageCrossFade/img3.jpg"> <img src="http://slayeroffice.com/code/imageCrossFade/img4.jpg"> <img src="http://slayeroffice.com/code/imageCrossFade/img5.jpg"> <img src="http://slayeroffice.com/code/imageCrossFade/img6.jpg"> </div> </body> </html> Style Sheet 1 Code: #imageContainer { height:309px; } #imageContainer img { display:none; position:absolute; top:0; left:0; } Style Sheet 2 Code: #imageContainer { position:relative; margin:auto; width:500px; border:1px solid #000; } JavaScript Code: window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init); var d=document, imgs = new Array(), zInterval = null, current=0, pause=false; function so_init() { if(!d.getElementById || !d.createElement)return; css = d.createElement("link"); css.setAttribute("href","xfade2.css"); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); d.getElementsByTagName("head")[0].appendChild(css); imgs = d.getElementById("imageContainer").getElementsByTagName("img"); for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0; imgs[0].style.display = "block"; imgs[0].xOpacity = .99; setTimeout(so_xfade,1000); } function so_xfade() { cOpacity = imgs[current].xOpacity; nIndex = imgs[current+1]?current+1:0; nOpacity = imgs[nIndex].xOpacity; cOpacity-=.05; nOpacity+=.05; imgs[nIndex].style.display = "block"; imgs[current].xOpacity = cOpacity; imgs[nIndex].xOpacity = nOpacity; setOpacity(imgs[current]); setOpacity(imgs[nIndex]); if(cOpacity<=0) { imgs[current].style.display = "none"; current = nIndex; setTimeout(so_xfade,1000); } else { setTimeout(so_xfade,50); } function setOpacity(obj) { if(obj.xOpacity>.99) { obj.xOpacity = .99; return; } obj.style.opacity = obj.xOpacity; obj.style.MozOpacity = obj.xOpacity; obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")"; } } |