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";
Related
I would like to generate a unique title when a user clicks on a link in this page:
When a user clicks on one of those links, the tab title should correspond to the csv.
Here is a little of my HTML for each page style (where the title tags are):
<title>Sortable & Responsive Table</title> //this is the current title that shows up on the tabs, but these must be unique, like Arc CSV or Coral CSV
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--[if !IE]><!-->
<style>
{
margin: 0;
padding: 0;
}
body {
font: 14px/1.4 Georgia, Serif;
}
#page-wrap {
margin: 50px;
}
p {
margin: 20px 0;
}
I have a single JavaScript file that parses for the csv that was clicked and loads that corresponding table within the link -- so I figure that generating a unique title would be just as simple (if not simpler):
Window.addEventListener ("DOMContentLoaded", function ()
{
var query = location.search;
query = query.slice(1);
var queryArray = query.split("&");
var file;
for (var i=0; i<queryArray.length; i++)
{
if (queryArray[i].slice(0, 4) === "csv=")
{
file = queryArray[i].slice(4);
}
}
var path = "../reservations/"+file+".csv";
d3.csv("../reservations/"+file+".csv", function(error, data) {
//generates unique table here
});
I'm not too familiar with JavaScript/HTML, but I'm always learning. Please let me know. Sorry if I missed anything, let me know if I should supply additional code/information. I appreciate it!
To change the title of a page is simple like that:
// this changes the title
document.title = "New Title"
// create a higher order function
function setTitle(title) {
document.title = title
}
// and use it like this..
setTitle("New Title")
Maybe something like this:
<head>
<title></title>
</head>
<body>
<li><a onclick="change(theFile)"></a></li>
<script>
var theFile = "What you want";
function change(csv){
document.title = csv;
};
</script>
</body>
In your javascript function, change these lines:
var path = "../reservations/"+file+".csv";
d3.csv("../reservations/"+file+".csv", function(error, data) {
//generates unique table here
});
to
var path = "../reservations/"+file+".csv";
d3.csv("../reservations/"+file+".csv", function(error, data) {
window.document.title=path; //// or whatever title you want to set
//generates unique table here
});
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.
I'm writing my first program to make an extension in Google chrome, i just took the "hello world" tutorial as example from here
This is my html file source code :
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
ad this is my javascript file source code :
var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=hello%20world&" +
"safe_search=1&" + // 1 is "safe"
"content_type=1&" + // 1 is "photos only"
"sort=relevance&" + // another good one is "interestingness-desc"
"per_page=20",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
var photos = req.responseXML.getElementsByTagName("photo");
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
for (var i = 0, photo; photo = photos[i]; i++) {
var img = document.createElement("image");
img.src = constructImageURL(photo);
document.body.appendChild(img);
}
}
// See: http://www.flickr.com/services/api/misc.urls.html
function constructImageURL(photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
The example is very simple and it works fine, but when add my own javascript instruction, it doesn't display it, the instruction that added is in showPhotos() function and it's :
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
in the result, i can see the other content but my 'h1' i don't see it.
i missed something ? can anyone help me please ?
Thanks
You're creating an element but you're not adding it to the page. So it can't be visible.
You can see it you add it, for example like this :
var element = document.createElement('h1');
element.appendChild(document.createTextNode ('tete '+document.location.href+'hgdfhgd'));
document.body.appendChild(element);
I'm using JavScript and jQuery to read an XML document and subsequently use the information from the XML to create HTML objects.
The main 'C' nodes in the XML document all have a type attribute, and depending on the type I want to run a function which will create a new html object using the other attributes assigned to that particular 'C' node node.
Currently, I have a for loop which extracts each 'C' node from the XML and also it's attributes (e.g. width, height, x, y).
Also inside the for loop, I have an if statement which checks the 'type' attribute of the current 'C' node being processed, and depending on the type it will run a different function which will then create a new HTML object with the attributes which have been drawn from the XML.
The problem is that there may be more than one 'C' node of the same type, so for example when I'm creating the function that will run when a 'C' node of 'type=1' is detected, I cannot use the 'var p = document.createElement('p')' because if a 'C' node of the same type comes up later in the loop it will clash and override that element with that variable that has just been created.
I'm not really sure how to approach this?
Here is my entire script. If you need me to elaborate on any parts please ask, I'm sure it's not written in the nicest possible way:
var arrayIds = new Array();
$(document).ready(function(){
$.ajax({
type: "GET",
url: "question.xml",
dataType: "xml",
success: function(xml)
{
$(xml).find("C").each(function(){
arrayIds.push($(this).attr('ID'));
});
var svgTag = document.createElement('SVG');
// Create question type objects
function ctyp3(x,y,width,height,baC)
{
alert('test');
var r = document.createElement('rect');
r.x = x;
r.y = y;
r.width = width;
r.height = height;
r.fillcolor = baC;
svgTag.appendChild(r);
}
// Extract question data from XML
var questions = [];
for (j=0; j<arrayIds.length; j++)
{
$(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){
// pass values
questions[j] = {
typ: $(this).attr('typ'),
width: $(this).find("I").attr('wid'),
height: $(this).find("I").attr('hei'),
x: $(this).find("I").attr('x'),
y: $(this).find("I").attr('x'),
baC: $(this).find("I").attr('baC'),
boC: $(this).find("I").attr('boC'),
boW: $(this).find("I").attr('boW')
}
alert($(this).attr('typ'));
if ($(this).attr('typ') == '3')
{
ctyp3(x,y,width,height,baC);
// alert('pass');
} else {
// Add here
// alert('fail');
}
});
}
}
});
});
My example uses the $.each() function in jQuery and adds the element to the <body> tag using a chained function so that you don't ever have to create a variable p.
Even though the author posted their code example after mine was written, I will leave it up here in case anyone else can benefit from it.
See it on jsFiddler: http://jsfiddle.net/gKN4V/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
var xmlString = '<root>'
+ '<C type="1" x="25" y="30" text="My cool div" />'
+ '<C type="2" x="50" y="75" text="My other div" />'
+ '<C type="1" x="100" y="10" text="My fun div" />'
+ '<C type="2" x="150" y="150" text="My awesome div" />'
+ '</root>';
$(function() {
var xml = $(xmlString);
$("C", xml).each(function(i,o) {
var node = $(o);
switch(node.attr("type")) {
case "1" :
$("<p />", {
"class" : "type1",
css : {
left :node.attr("x") + "px",
top : node.attr("y") + "px"
}
}).text(node.attr("text")).appendTo("body");
break;
case "2":
$("<div />", {
"class" : "type2",
css : {
left :node.attr("x") + "px",
top : node.attr("y") + "px"
}
}).text(node.attr("text")).appendTo("body");
break;
}
});
});
</script>
<style type="text/css">
.type1 {
position: absolute;
border: solid 1px gray;
font: normal 12px Arial, Helvetica, sans-serif;
}
.type2 {
position: absolute;
border: solid 1px green;
font: bold 12px Arial, Helvetica, sans-serif;
color: green;
}
</style>
</head>
<body>
</body>
</html>
I cannot use the 'var p = document.createElement('p')' because if a 'C' node of the same type comes up later in the loop it will clash and override that element
Just don't use fixed variable names. Let your loop add elements to an array instead:
var elementList = [];
var Cs = xml.getElementByTagName("C");
for (var i=0; i<Cs.length; i++) {
elementList.push( whateverYourFunctionIsThatCreatesHtmlNodes(Cs[i]) );
}
or add them right to the DOM in the loop body.
I have this thing working mostly. What I don't get is, if I have the file on my desktop and drag it into a browser, it works. If I upload the same file to my website and visit it, it displays nothing in Firefox. Last night it worked in Safari, but today it does not. Is something really weird in this code?
Here is the pastie in case pasting all this in here does not work :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{
background: #353535;
color: #fff;
font-size: 62.5%;
padding: 10px;
}
p{
font-size: 1.6em;
font-family: Arial, "MS Trebuchet", sans-serif;
}
span{
font-size: 1.6em;
font-variant: small-caps;
}
ul {
list-style: none;
}
li {
font-size: 1.6em;
text-transform: capitalize;
}
img{
float: left;
margin: 10px;
}
</style>
<!-- actual api http://api.tinychat.com/designtalk.json -->
<!-- testing file test.json -->
<script>
$(document).ready(function(){
$.getJSON("http://api.tinychat.com/designtalk.json",
function(data){
$('#name').append(data.name);
$('#topic').append(data.topic);
$('#broadcast').append(data.broadcaster_count);
$('#count').append(data.total_count);
$('#priv').append(data.priv);
if(!data.name)
{
alert("Room empty!")
}
var $nameList = $('<ul></ul>');
$.each(data.names, function (i, val) {
$('<li></li>').appendTo($nameList).html(val);
});
$('#container').append($nameList);
$.each(data.pics, function (i, val) {
$("<img/>").attr("src", val).appendTo("#images");
});
});
});
</script>
</head>
<body>
<p id="name"><span>Room Name:</span> </p>
<p id="topic"><span>Current Topic:</span> </p>
<p id="broadcast"><span>Number Broadcasting:</span> </p>
<p id="count"><span>Total in Room:</span> </p>
<p id="priv"><span>Number with Privileges:</span> </p>
<div id="container"><span>Who is Online?</span></div>
<div id="images"></div>
</body>
</html>
In the callback function you would just go through each element. Let's say you wanted to append the names to a div with the id of namesDiv you might do this:
$.get("something.aspx", function(json) {
for(var i =0; i< json.names.length; i++)
{
$('#namesDiv').append(json.names[i]);
}
You can create HTML elements programmatically, to build an HTML List for example:
$('<div></div>').appendTo('#container').html(data.title);
var $nameList = $('<ul></ul>');
$.each(data.names, function (i, val) {
$('<li></li>').appendTo($nameList).html(val);
});
$('#container').append($nameList);
Example here.
Without jQuery:
var container = document.getElementById('container'),
title = document.createElement('div'),
nameList = document.createElement('ul'), li;
title.innerHTML = data.title;
for (var i = 0; i < data.names.length; i++) {
li = document.createElement('li');
li.innerHTML = data.names[i];
nameList.appendChild(li);
}
container.appendChild(title);
container.appendChild(nameList);
Example here.
Edit: In response to your comment, you were missing the Flickr specific parameter jsoncallback to make the JSONP request, and also in the structure of the JSON response the names member doesn't exists, I think you mean items.
Check your feed example fixed here.
There is a firefox plugin which formats json data. https://addons.mozilla.org/en-US/firefox/addon/10869
This is assuming you only want to learn what the json data looks like and hence start programming in it...
Very long in the tooth, but it does take care to recognize that properties of your object may have their own properties as well. Assumes a DIV element (or similar) exists with an ID of "content."
function WriteObject(obj, tabs)
{
tabs = tabs || 0;
var padding = "";
for(var i = 0; i < tabs; ++i)
{
padding += "\ ";
}
for(var prop in obj)
{
if(typeof(obj[prop]) === "object")
{
if(obj[prop].constructor === Array)
{
var str = obj[prop].join(",");
$("#content").append(padding + prop + ": " + str + "<br />");
}
else
{
$("#content").append(padding + prop + "<br />");
WriteObject(obj[prop], tabs + 1);
}
}
else
{
$("#content").append(padding + prop + ": " + (obj[prop] ? obj[prop] : "null") + "<br />");
}
}
}
You can try the page below:
In modern browsers you don't need anymore the json2.js library from json.org
<html>
<head>
<script src="http://www.json.org/json2.js"></script>
</head>
<body>
<pre id="res"></pre>
<script>
var json = {
"title":"No title",
"names":["", "dave", "jeff", "sean", "", ""],
"total_people":3
};
document.getElementById('res').innerHTML = JSON.stringify(json, null, 2);
</script>
</body>
</html>