I am trying to randomise a image in a background, I am having problems because there is content already in the div
this is what i got so far
<div class="welcome-inner">
<script type="text/javascript">
<!--
var imlocation = "welcome/";
var currentdate = 0;
var image_number = 0;
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(3)
image[0] = 'background1.jpg'
image[1] = 'background2.jpg'
image[2] = 'background3.jpg'
var rand = 60/image.length
function randomimage() {
currentdate = new Date()
image_number = currentdate.getSeconds()
image_number = Math.floor(image_number/rand)
return(image[image_number])
}
document.write("<img src='" + imlocation + randomimage()+ "'>");
//-->
</script>
CONTENT
</div>
the div welcome-inner already has styling in the css
.row-welcome {
border-bottom: 0;
width: 100%;
margin: 0 auto;
overflow: auto;
margin-top: -20px;
background-position: 50% 50%;
background-size: cover;
border-bottom: 1px solid #1e346a;
}
welcome-inner did have a background image but I removed the line to try to get this to work
The problem I am having is that the images are showing up but pushing my content down.
how do I adapt this to make it work?
You're going to need to set the background-image style (if you're using jQuery this will be easier). So, instead of creating an tag which goes in the normal document flow, something more like this:
$("#welcome-inner").style("background-image", imlocation + randomimage());
And change "#welcome-inner" to whatever the selector is for the DOM element you want to set the background-image on.
I think your entire approach is incorrect. Try using .sort(), like:
var doc = document;
function E(e){
return doc.getElementById(e);
}
function range(least, greatest){
var r = [];
for(var i=0,n=least; n<=greatest; i++,n++){
r[i] = n;
}
return r;
}
var rng = range(1, 3);
rng.sort(function(){
return Math.round(Math.random())-0.5;
});
for(var i in rng){
var img = new Image();
img.src = 'welcome/background"+rng[i]+".jpg';
// If you add an id called pickAnId to your welcome-inner className div then
E('pickAnId').appendChild(img);
}
Related
I'm working on a Javascript assignment that splits the page into two div elements then appends the div on the left with randomly placed images, then I used .cloneNode() to duplicate on the right, minus the last child image.
That part of it works fine, but I am then supposed to add an event handler to the last element of the left div, but when I try to do this the lastElementChild() method returns null even though the div has the expected child nodes. The code is below and I've commented where the problem is. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
<script>
<!-- everything here works fine -->
function generateFaces(){
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
</script>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
<!-- problem script here -->
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
</script>
</body>
</html>
The body's onload event will not fire until after the javascript in your 'problem script' runs.
The order of execution here is basically:
h1, p, #left, and #right get appended to the DOM
script #1 runs, logging the empty #left div and the null lastElementChild.
body onload event fires and script #2 runs (the generateFaces() function). At this point, the <img> tags are inserted into the DOM.
The fix is to make sure that script #1 runs after #2:
<body onload="handleLoad()">
and the JS:
function handleLoad() {
generateFaces()
logStuff()
}
function logStuff() {
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // logs <img>
}
It might appear, in the console, that #left has images in it at the time that script #1 runs. This is just a quirk of the console; the actual logging happens asynchronously, and since the referenced variable changes in the meantime, the value actually logged is different than what it was when console.log() was called.
You can see this behavior by varying a setTimeout duration on the generateFaces() function call:
function generateFaces() {
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++) {
var random_x = Math.random() * 400;
var random_y = Math.random() * 400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style", "top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
setTimeout(generateFaces, 250) // play with this value
img {
position: absolute
}
div {
position: absolute;
height: 500px;
width: 500px
}
#right {
border-left: solid black;
left: 500px
}
<h1> Game </h1>
<p> Instructions </p>
<div id="right"></div>
<div id="left"> </div>
Oh, and note that your generateFaces() function currently creates multiple elements in the DOM with the same id. You're gonna want to fix that.
Your generateFaces() function is called when the body is loaded.
but your second script runs when the window is loaded.
So when the second script runs there is no temp.lastElementChild and you get null.
You can slove is like this
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute, height: 30px; width: 30px;}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
function generateFaces()
{
console.log('y');
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
loaded();
}
<script>
function loaded() {
var temp = document.getElementById("left");
console.log(temp);
var temp2 = temp.lastElementChild;
console.log(temp2);
}
I'm trying to practice my scripting by making a Battleship game. As seen here.
I'm currently trying to make the board 2D. I was able to make a for-loop in order to make the board, however, due to testing purposes, I'm just trying to make the board, upon clicking a square, it turns red... But, the bottom square always lights up. I tried to debug it by making the c value null, but then it just stops working. I know it's not saving the c value properly, but I'm wondering how to fix this.
Do I have to make 100 squares by my self or can I actually have the script do it?
maincansize = 400;
document.getElementById("Main-Canvas").style.height = maincansize;
document.getElementById("Main-Canvas").style.width = maincansize;
document.getElementById("Main-Canvas").style.position = "relative";
var ize = maincansize * .1;
for (var a = 0; a < 10; a++) {
for (var b = 0; b < 10; b++) {
var c = document.createElement("div");
var d = c;
c.onclick = function() {
myFunction()
};
function myFunction() {
console.log("A square was clicked..." + c.style.top); d.style.backgroundColor = "red";
}
c.style.height = ize;
c.style.width = ize;
c.style.left = b * ize;
c.style.top = a * ize;
c.style.borderColor = "green";
c.style.borderStyle = "outset";
c.style.position = "absolute";
console.log(ize);
document.getElementById('Main-Canvas').appendChild(c);
} //document.getElementById('Main-Canvas').innerHTML+="<br>";
}
#Main-Canvas {
background-color: #DDDDDD;
}
<div>
<div id="header"></div>
<script src="HeaderScript.js"></script>
</div>
<div id="Main-Canvas" style="height:400;width:400;">
</div>
Here's your code with some fixes:
adding 'px' to style assignment
passing the clicked element to myFunction
var maincansize = 400;
document.getElementById("Main-Canvas").style.height = maincansize;
document.getElementById("Main-Canvas").style.width = maincansize;
document.getElementById("Main-Canvas").style.position = "relative";
var ize = maincansize * .1;
for (var a = 0; a < 10; a++) {
for (var b = 0; b < 10; b++) {
var c = document.createElement("div");
c.onclick = function(ev) {
myFunction(ev.currentTarget);
};
function myFunction(el) {
console.log("A square was clicked...");
el.style.backgroundColor = "red";
}
c.style.height = ize+'px';
c.style.width = ize+'px';
c.style.left = (b * ize)+'px';
c.style.top = (a * ize)+'px';
c.style.borderColor = "green";
c.style.borderStyle = "outset";
c.style.position = "absolute";
document.getElementById('Main-Canvas').appendChild(c);
}
}
#Main-Canvas {
background-color: #DDDDDD;
}
<div id="Main-Canvas" style="height:400;width:400;">
</div>
Here's a solution with major revamps. Since you're using a set width for the container element of your board cells you can float the cells and they will wrap to the next line. Absolute positioning tends to be a bit of a bugger. If you want 10 items per row it's as easy as:
<container width> / <items per row> = <width>
Using document fragments is faster than appending each individual element one at a time to the actual DOM. Instead you append the elements to a document fragment that isn't a part of the DOM until you append it. This way you're doing a single insert for all the cells instead of 100.
I moved some of the styling to CSS, but could easily be moved back to JS if you really need to.
function onCellClick() {
this.style.backgroundColor = 'red';
console.log( 'selected' );
}
var main = document.getElementById( 'board' ),
frag = document.createDocumentFragment(),
i = 0,
len = 100;
for ( ; i < len; i++ ) {
div = document.createElement( 'div' );
div.addEventListener( 'click', onCellClick, false );
frag.appendChild( div );
}
main.appendChild( frag );
#board {
width: 500px;
height: 500px;
}
#board div {
float: left;
box-sizing: border-box;
width: 50px;
height: 50px;
border: 1px solid #ccc;
}
<div id="board"></div>
I'm trying to prevent my thumbnails from stretching on my website when search results are shown.
My website is www.thehungryeurasian.com
To search for a label, select 'I'm hungry for' in navigation bar, then click any of the options below.
This is the javascript that I used:
<script type='text/javascript'>
var thumbnail_mode = "no-float" ;
summary_noimg = 300;
summary_img = 350;
img_thumb_height = 200;
img_thumb_width = 300;
</script>
<script type='text/javascript'>
//<![CDATA[
function removeHtmlTag(strx,chop) {
if(strx.indexOf("<")!=-1) {
var s = strx.split("<");
for(var i=0;i<s.length;i++) {
if(s[i].indexOf(">")!=-1) {
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
function createSummaryAndThumb(pID){
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = summary_noimg;
if(img.length>=1) {
imgtag = '<span style="float:left; padding:0px 10px 5px 0px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height +'px"/></span>';
summ = summary_img;
}
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>';
div.innerHTML = summary;
}
//]]>
</script>
However, every time I've tried to edit the size of the image in CSS, it would edit all the images on my website, rather than just those that appear in the search results.
Set only the following code in your CSS file. Use selectors to target more specific images.
/* CSS */
img { height: auto; }
or
/* CSS */
.post-body img { height: auto; }
I am working on a wordpress website who's client would like me to adjust our AdSanity plugin to display groups of ads in a rotating image gallery fashion like the ones on this page. The leaderboard ads for sure are AdSanity run. I was able to stem from viewing the source that this is the script I need:
$(function() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
};
//////////
$('#slides').slidesjs({
width: 552,
height: 426,
navigation: false,
play: {
auto: true
}
});
//////////
$('.three_lines_fixed').each(function() {
$clamp(this, {
clamp: 3
});
});
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
}
var site_url = $("body").attr("site_url");
$("#brpwp_wrapper-2 ul").append("<li style='text-align: center;'><a class='widgetized_read_more' href='" + site_url + "/2013'>Read More</a></li>")
/**/
And some of that I don't believe I need, like the three_lines_fixed or the slides. I also have the CSS used for #adspace:
div.header div#adspace {
float: right;
max-width: 728px;
max-height: 90px; }
div.header div#adspace img {
float: right; }
There is also this CSS:
div#page .main_content ul.widgets li.adspace {
display: none; }
On my site http://dsnamerica.com/eisn/ I want the 300px width ads on the right sidebar to rotate like those on the Vype site. These ads though are not listed with ul and li, they are divs.
So far I've added this to my header.php theme file right before the closing tag:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/fading-ads.js"></script>
And in that file (js/fading-ads.js), I have this:
function adsanitygroup() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
};
};
}
That is my attempt to define the function and clean out what I didn't need. I don't think, no, I know it's not right. So I'll put my questions in a list, since this post is already wordy.
1) Did I link the js file correctly in the theme's header.php file? It's right before the closing </head> tag.
2) Do I need the second CSS part that says "display: none" and if so, how do I change the CSS to work with divs instead of ul and li? Do I just change div#page .main_content ul.widgets li.adspace {
display: none;}
to
div#page .main_content .widgets .adspace {
display: none; }
then add the class .adspace to the widget?
See, I have been trying to get this to work for a couple days now and I've thought so much on it I'm not making cohesive theories anymore, just shots in the dark. How to solve this?
I hope that someone will know how to help me with this problem, I am new to javaScript and XML. Basically I have the xml file with list of products, I have managed to dynamically load the data into an ul li list in my html page, the li elements has title and image, and now I need to be able to click on this li element and load remaining data for a specific product into a new page (or div). I am getting the "Uncaught ReferenceError: i is not defined" My question is how could I load the correct remaining data after clicking on a specific product from the list of products. (I hope that my explanation is clear enough) here is my code, the first function produces the ul li list in the html page, the displayPRInfo() function should load the data into showPrInfo div for any product which was clicked.
please help me, any help appreciated , thanks for reading.
function loadProducts() {
var liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
var divOpen=("</p><div class='prod-sq-img'>");
var closingTags=("</div></li>");
var txt;
var image;
var title;
var x=xmlDoc.getElementsByTagName("product");
for (i=0;i<x.length;i++)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
}
function displayPRInfo(i)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
euPriceRet=(x[i].getElementsByTagName("euror")[0].childNodes[0].nodeValue);
euPriceTrade=(x[i].getElementsByTagName("eurot")[0].childNodes[0].nodeValue);
euPriceSet=(x[i].getElementsByTagName("eset")[0].childNodes[0].nodeValue);
minimumQuantity=(x[i].getElementsByTagName("mqty")[0].childNodes[0].nodeValue);
description=(x[i].getElementsByTagName("desc")[0].childNodes[0].nodeValue);
prBigImg=(x[i].getElementsByTagName("pimgfile")[0].childNodes[0].nodeValue);
prInfo=title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
document.getElementById("showPrInfo").innerHTML=prInfo;
}
You can use jQuery to manipulate xml and set onclick events.
function loadProducts() {
var products = $(xmlDoc).find('product');
for (var i = 0; i < products.length; i++) {
$('#ulList').append('<li id="product_' + i + '"><p>' + $(products[i]).find('title').text() + '</p><div class="prod-sq-img">' + $(products[i]).find('imgfile').text() + '</div></li>');
$('#product_' + i).click(displayPRInfo.bind($('#product_' + i), products[i]));
}
}
function displayPRInfo(xmlProduct) {
var title= $(xmlProduct).find('title).text();
var euPriceRet = $(xmlProduct).find('euror').text();
var euPriceTrade = $(xmlProduct).find('eurot').text();
var euPriceSet = $(xmlProduct).find('eset').text();
var minimumQuantity = $(xmlProduct).find('mqty').text();
var description = $(xmlProduct).find('desc').text();
var prBigImg = $(xmlProduct).find('pimgfile').text();
var prInfo = title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
$('#showPrInfo').html(prInfo);
}
I haven't tried the whole script but for sure you have to move this:
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>")
into the for loop
for (i=0; i<x.length; i++) {
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
where acctually i is defined
I found this and it helped me a bit, the thing is that I want to load images by request, not loading them all at once but by clicking a button and set the img src with the xml data, I have this...
<!doctype html>
<html lang="es">
<head>
<style>
#iosslider_nav {
height: 13px;
right: 10px;
/* align right side */
/*left: 10px;*/
/* align left side */
bottom: 10px;
/*position: absolute;*/
/* set if needed */
/*margin-top: 10px;*/
/* remove if position is absolute */
}
#iosslider_nav .btn {
width: 13px;
height: 13px;
background: #eaeaea;
margin: 0 5px 0 0;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
cursor: pointer;
float: left;
/* ie 7/8 fix */
background: url('../images/bull_off.png') no-repeat\9;
}
</style>
</head>
<body>
<div id="ninja_slider"></div>
<div id="iosslider_nav"></div>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var xmlDoc = loadXMLDoc("xml/xml_data.xml");
// generic load xml data function
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // code for IE5 and IE6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", filename, false);
xhttp.send();
return xhttp.responseXML;
}
set_slider();
//set_navigation('xml/xml_data.xml', 'iosslider_nav');
function set_slider() {
var item_div = $(xmlDoc).find('desk');
var item_btn = $(xmlDoc).find('desk');
var item_img = $(xmlDoc).find('desk');
// Object.bind() handler for ie 7/8
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
// create main div's
for (var i = 0; i < item_div.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="" class="ninja_item"></div>');
$('#item_div' + i).on('click', load_current.bind($('#item_div' + i), item_div[i]));
}
// load first element
$('#ninja_slider #item_div0 .item_anchor img').attr('src', $(item_img[0]).find('image').text());
// create nav div's
for (var i = 0; i < item_btn.length; i++) {
$('#iosslider_nav').append('<div id="item_btn' + i + '" class="btn"></div>');
$('#item_btn' + i).on('click', load_current.bind($('#item_btn' + i), item_btn[i]));
}
}
function load_current(xmlData) {
var image = $(xmlData).find('image').text();
var src = image;
//console.log(image);
var item_img = $(xmlDoc).find('desk');
for (var i = 0; i < item_img.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="' + $(item_img[i]).find('image').text() + '" class="ninja_item"></div>');
}
}
function set_navigation(url, id) {
$.ajax({
url: url,
async: false,
type: "GET",
data: "xml",
success: function (xml) {
$(xml).find("desk").each(function () {
var item_nav = document.getElementById(id),
click_item = document.createElement("div");
item_nav.appendChild(click_item);
click_item.className = click_item.className + "btn";
});
}
});
}
</script>
</body>
</html>
hope it makes sense...