java script: swapping technique, adding random text - javascript

In my code I have the image that swaps to another one image each time I click on it with the mouse. I have difficulties with adding a random text to the second (swapped) image. The text should not appear when i see the first image.
Here is my code. There are some mistakes in java script when I was trying to write a code for the random text. Please, help me to correct.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1></h1>
<div id="cookie" class='whole'></div>
</div>
<p id="demo"></p>
<script src="js/cookies.js"></script>
</body>
</html>
js code:
var lock = document.getElementById('cookie');
var state = 'orange';
function swapImage(){
if (state === 'orange'){
lock.className = 'cracked';
state = 'blue';
}else{
lock.className = 'whole';
state = 'orange';
}
}
lock.addEventListener('click', swapImage, false);
var r_text = new Array ();
r_text[0] = "All the leaves are brown";
r_text[1] = "And the sky is grey";
r_text[3] = "On a winter's day";
r_text[4] = "I'd be safe and warm";
r_text[6] = "California dreaming, On such a winter's day";
var i = Math.floor(7*Math.random())
function fortune() {
document.write(r_text[i]);
}
var elText = document.getElementById('cookies');
elText.addEventListener('click', fortune, false);
css:
#cookie{
width: 360px;
height: 216px;
margin: 100px auto;
margin-top: 10px;
}
.whole {
background: url("../images/whole.png");
}
.cracked {
background: url("../images/cracked.png");
}

You have to run var i = Math.floor(7*Math.random()) inside your fortune function, or i will be the same as it was before.

Related

replace text from string not working javascript

i cant seem to get this code to work i’ve been trying at it for hours i'm trying to make a formatting system for html markup and later js and css once i can get this working the desired outcome here to to have a list of items in the var l string detect in the contenteditable <p>tag but cant get it to give me any outcome same issue when applying a filter to replace words in a string with </tag> i'm not sure if this is a syntax issue or just something i'm missing but i cant for the life of me find the error in my code any help is appreciated
<html>
<style>
.form {
color: green;
background: black;
}
</style>
<body>
<button onclick="register()">format</button>
<p id="demo" contenteditable>tags to format- <head> <body> <html> <span></p>
<script>
function register() {
let text = document.getElementById("demo").innerHTML;
var l = ["head","body","html","span"];
for(let i = 0; i < l.length; i++) {
setTimeout(function() {
document.getElementById("demo").innerHTML =
text.replace("<"+ l[i] +">","<span class='form'><"+ l[i] +"></span>");
},500);
}
}
</script>
</body>
</html>
You were overriding the innerHTML each time. Only change the innerHTML once.
function register() {
let text = document.getElementById("demo").innerHTML;
var l = ["head","body","html","span"];
for(let i = 0; i < l.length; i++) {
text =
text.replace("<"+ l[i] +">","<span class='form'><"+ l[i] +"></span>");
}
document.getElementById("demo").innerHTML = text;
}
.form {
color: green;
background: black;
}
<button onclick="register()">format</button>
<p id="demo" contenteditable>tags to format- <head> <body> <html> <span></p>

How transform a value into a html element in p5.js?

I’m trying to make a single web page with p5.js, but at some moment I create an input and the value of the input I want to transform into a html tag (more specifically ‘h3’). I already tried the “.html()” as this example: [examples | p5.js], but for some reason this doesn’t work in my context. I’ll let my code below:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputDiv.parent("sobre");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName.html(userName);
}
I need this in as a variable, because after I’ll format it inside a div in css. Is there another way to transform this value?
Thanks
If I'm understanding correctly, you're wanting to output the name that's entered into a h3 element?
In that case you could just use:
yourName = createElement('h3', userName);
like they've done in that reference you linked.
Here's a running example:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName = createElement('h3', userName);
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

How To Make Next Scene Insert Below Instead of Having It Create A New Page

Basically, I'm making a text game. The problem is whenever you click on the button, it makes it a whole new page. I want to insert the new scene below the old, like a texting app. I cannot figure it out no matter what I do, I keep breaking the Javascript.
//these variables connect our code with the 'id' on the html
//we can then manipulate the variables and it will manipulate the html
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var hero;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
hero = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", hero);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
//this is what moves the game along
var advanceTo = function(s) {
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
//this is the object that holds each scenario, the more you add the more options there are
//scenario = {}
var scenario = {
one: {
image: "http://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "H-hello? Yes! Yes! It's working! Is anyone there? Hello? If you're there, what's your name?",
},
two: {
image: "http://s9.postimg.org/9p8m7v1u7/6899639786_d517c4cce3_z.jpg", //house
text: "Your dog yanks at the leash. You hear dogs barking and see an old abandoned house. Strangely, the door is wide open. What do you want to do?",
buttons: [["Turn and run", "advanceTo(scenario.three)"],["Enter The House", "advanceTo(scenario.four)"]]
},
three: {
image: "http://1.bp.blogspot.com/-83pWE4JxQxM/ViiOd_7nGTI/AAAAAAAADUg/yCJ8iAB-gMY/s1600/postapoc5.jpg",//"http://s4.postimg.org/t1g20apst/261819008_d4316c1bdf_o.jpg",
text: "A wild gang of rabid dogs are gaining on you. Against your better judgement you enter the creepy house for saftey. Your dog is whincing and may be injured.",
buttons: [["continue", "advanceTo(scenario.four)"]]
},
four: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "Your dog has run, barking loudly, into the basement. You wonder what's down there. The door jammed when you slammed it behind you. You are going to need something to pry it back open",
buttons: [["Follow your Dog Downstairs", "advanceTo(scenario.five)"],["Search the Kitchen for a knife", "advanceTo(scenario.five)"]]
},
five: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "TO BE CONTINUED...",
},
};
//this is the code that starts the game
advanceTo(scenario.one);
HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>The Help</title>
<link rel="stylesheet" href="css/style.css">
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
</head>
<body>
<html>
<body>
<div id="images">
</div>
<div id="text">
</div>
<input id="input" onkeydown='submitDogName(this)' placeholder='What is your name?'>
<div id="buttonBox">
</div>
</body>
</html>
<script src="js/index.js"></script>
</body>
</html>
What would make it so instead of changing to a complete different page, it inserts it below, again like a message?
There are some problem you must deal with. See as below.
Must add a condition for falsy value like undefined. See the following modification.
var changeButtons = function(buttonList) {
if(!buttonList) return; // Here.
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
Use single quote to quote value of url in background image. See the following modification.
var changeImage = function(img) {
images.style.backgroundImage = "url('" + img + "')"; // Here.
};
The height of div element is 0 if there is no content inside so you have to set height a specific value by CSS or JavaScript. You can see the default size of div element from reference. See below CSS content.
#images {
background-size: 100% 100%;
height: 200px;
}
Now, you can see the complete example as below and you may realize onkeydown='submitDogName(this)' will throw exception so I removed it. The below example is just a executable demo at the moment. You can see EDIT for the version of texting APP which you may need.
//these variables connect our code with the 'id' on the html
//we can then manipulate the variables and it will manipulate the html
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var hero;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
if (event.key == "Enter" || event.keyCode == 13) {
hero = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", hero);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url('" + img + "')";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
if(!buttonList) return;
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
//this is what moves the game along
var advanceTo = function(s) {
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
//this is the object that holds each scenario, the more you add the more options there are
//scenario = {}
var scenario = {
one: {
image: "http://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "H-hello? Yes! Yes! It's working! Is anyone there? Hello? If you're there, what's your name?",
},
two: {
image: "http://s9.postimg.org/9p8m7v1u7/6899639786_d517c4cce3_z.jpg", //house
text: "Your dog yanks at the leash. You hear dogs barking and see an old abandoned house. Strangely, the door is wide open. What do you want to do?",
buttons: [["Turn and run", "advanceTo(scenario.three)"],["Enter The House", "advanceTo(scenario.four)"]]
},
three: {
image: "http://1.bp.blogspot.com/-83pWE4JxQxM/ViiOd_7nGTI/AAAAAAAADUg/yCJ8iAB-gMY/s1600/postapoc5.jpg",//"http://s4.postimg.org/t1g20apst/261819008_d4316c1bdf_o.jpg",
text: "A wild gang of rabid dogs are gaining on you. Against your better judgement you enter the creepy house for saftey. Your dog is whincing and may be injured.",
buttons: [["continue", "advanceTo(scenario.four)"]]
},
four: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "Your dog has run, barking loudly, into the basement. You wonder what's down there. The door jammed when you slammed it behind you. You are going to need something to pry it back open",
buttons: [["Follow your Dog Downstairs", "advanceTo(scenario.five)"],["Search the Kitchen for a knife", "advanceTo(scenario.five)"]]
},
five: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "TO BE CONTINUED...",
},
};
//this is the code that starts the game
advanceTo(scenario.one);
#images {
background-size: 100% 100%;
height: 200px;
}
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8"/>
<title>The Help</title>
<link rel="stylesheet" href="css/style.css"/>
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"/>
</head>
<body>
<div id="images">
</div>
<div id="text">
</div>
<input id="input" placeholder='What is your name?'>
<div id="buttonBox">
</div>
<script src="js/index.js"></script>
</body>
</html>
EDIT
I think this is what you look for. Check it and tell me whether it is or not.
//these variables connect our code with the 'id' on the html
//we can then manipulate the variables and it will manipulate the html
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var hero;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
if (event.key == "Enter" || event.keyCode == 13) {
hero = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", hero);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url('" + img + "')";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
if(!buttonList) return;
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
var appendHistory = function() {
var historyDiv = document.getElementById("history");
var historyItemDiv = document.createElement("div");
historyItemDiv.appendChild(images.cloneNode(true));
historyDiv.appendChild(historyItemDiv);
}
//this is what moves the game along
var advanceTo = function(s) {
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
if(!s.isLast) appendHistory();
};
//this is the object that holds each scenario, the more you add the more options there are
//scenario = {}
var scenario = {
one: {
image: "http://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "H-hello? Yes! Yes! It's working! Is anyone there? Hello? If you're there, what's your name?",
isLast: false
},
two: {
image: "http://s9.postimg.org/9p8m7v1u7/6899639786_d517c4cce3_z.jpg", //house
text: "Your dog yanks at the leash. You hear dogs barking and see an old abandoned house. Strangely, the door is wide open. What do you want to do?",
buttons: [["Turn and run", "advanceTo(scenario.three)"],["Enter The House", "advanceTo(scenario.four)"]],
isLast: false
},
three: {
image: "http://1.bp.blogspot.com/-83pWE4JxQxM/ViiOd_7nGTI/AAAAAAAADUg/yCJ8iAB-gMY/s1600/postapoc5.jpg",//"http://s4.postimg.org/t1g20apst/261819008_d4316c1bdf_o.jpg",
text: "A wild gang of rabid dogs are gaining on you. Against your better judgement you enter the creepy house for saftey. Your dog is whincing and may be injured.",
buttons: [["continue", "advanceTo(scenario.four)"]],
isLast: false
},
four: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "Your dog has run, barking loudly, into the basement. You wonder what's down there. The door jammed when you slammed it behind you. You are going to need something to pry it back open",
buttons: [["Follow your Dog Downstairs", "advanceTo(scenario.five)"],["Search the Kitchen for a knife", "advanceTo(scenario.five)"]],
isLast: false
},
five: {
image: "http://s6.postimg.org/kz5m1cnkh/2919478782_c343d14be6_b.jpg",
text: "TO BE CONTINUED...",
isLast: true
},
};
//this is the code that starts the game
advanceTo(scenario.one);
#images {
background-size: 100% 100%;
height: 200px;
}
#history > div:last-child {
display: none;
}
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8"/>
<title>The Help</title>
<link rel="stylesheet" href="css/style.css"/>
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"/>
</head>
<body>
<div id="history"></div>
<div id="images"></div>
<div id="text"></div>
<input id="input" placeholder='What is your name?'/>
<div id="buttonBox"></div>
<script src="js/index.js"></script>
</body>
</html>

Picture not loading properlly

Good day! I am trying to set a div's background image source with javascript and It doesn't seem to work. I get a weird error in the console from which I have no idea what to made of.
The code may seem a bit lengthy but I will try to make it as clear as possible:
The style basically contains 3 classes. 1 of them is the big box in which the picture and the text are stored. The others are just for the picture (with size) and the label (again with size).
The body contains a simple empty div element which will be dynamically field.
What is left is the javascript file: an array, the object from which the "news"'s different properties will be read (like title, views, image source)
and finally the only function which basically creates new div elements, gives them classes and appends them to the main one. The error is somewhere here.
The entire source code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.newsBox {
width:600px;
height:100px;
background-color:#B3CFDB;
float:left;
border-bottom: solid 1px;
border-bottom-color: #B9DDED;
}
.newsPic {
width:96px;
height:96px;
float:left;
margin-left: 4px;
margin-top:2px;
}
.newsLabel {
height:75px;
width: 500px;
background-color: white;
margin-top:20px;
float:left;
}
</style>
</head>
<body>
<div id="main" class="content"></div>
</body>
</html>
<script>
//create the object array and dummies
var arr = [];
var news = {
title: "",
views: 0,
srs: ""
};
var one = Object.create(news);
one.title = "Bender";
one.views = 132;
srs = "Bender.gif";
arr.push(one);
var two = Object.create(news);
two.title = "Salvation is upon us";
two.views = 777;
srs = "fryFuturama.jpg";
arr.push(two);
var three = Object.create(news);
three.title = "This website is a joke";
three.views = 0;
srs = "fry.jpg";
arr.push(three);
//Set up
var main = document.getElementById("main");
function loadNews() {
for (var i = 0; i < arr.length; i++) {
var p = document.createElement("DIV");
p.className = "newsBox";
main.appendChild(p);
var p1 = document.createElement("DIV");
p1.className = "newsPic";
p1.style.backgroundImage = "url(" + arr[i].srs + ")";
p.appendChild(p1);
var p2 = document.createElement("DIV");
p2.className = "newsLabel";
p2.innerHTML = arr[i].title + "</br></br>" + "Views: " + arr[i].views;
p.appendChild(p2);
}
}
loadNews();
</script>
EDIT: The error: Resource interpreted as Image but transferred with MIME type text/html: "file:///C:/Users/SameTime/Desktop/ObjectSetBackgroundImage.html"
A short answer to your big wall of code
change your
srs = "Bender.gif";
to
one.srs = "Bender.gif";

Categories

Resources