var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://spreadsheets.google.com/feeds/cells/1PzTMW6xH5cjLgvLn_LOq25XEbmrCw2MP9C9vvt4rhoM/1/public/full?alt=json')
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
var TEXT = ourData.feed.entry[2].gs$cell.inputValue;
var IMG = ourData.feed.entry[3].gs$cell.inputValue;
console.log(TEXT);
console.log(IMG);
document.getElementById('testoutput').innerHTML = TEXT;
document.getElementById('backgroundIMG').style.backgroundImage = "url('IMG')";
};
ourRequest.send();
html, body {
height: 100%;
margin: 0;
overflow: hidden; /* Hide scrollbars */
}
div {
text-align: left;
min-height: 100%;
font-family: motiva-sans, sans-serif;
font-weight: 800;
font-size: 15vw;
padding: 15px;
padding-top: 30px;
padding-left: 10%;
}
<html lang="en">
<head>
<link rel="stylesheet" href="https://use.typekit.net/vbl6jef.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
<meta charset="utf-8">
<title>Google Sheets - Werkend</title>
</head>
<body>
<div id="backgroundIMG"><div>
<div id="testoutput"></div>
</body>
</html>
I'm working on a HTML document that gets its styling from Google Sheets JSON data. So far it works for setting properties such as backgroundColor.
Right now i'm trying to set the backgroundImage and have set a variable that contains the url:
document.getElementById('backgroundIMG').style.backgroundImage = "url('IMG')";
When I console.log the variable it returns the url just fine. When I place the URL directly into the code above, it works. When I put the variable in the code (like shown above) it won't load the URL.
My limited knowledge stops me from searching the right terms on what is going on here. I have tried reading up on variables but no succes yet.
Can anyone point me in the right direction by either telling me what to read up on or by offering a sollution based on my code below?
It's not using the IMG variable, just IMG as a string, so try:
document.getElementById('backgroundIMG').style.backgroundImage = "url(" + IMG + ")";
Adding a variable to a string:
"Traditional" ways (plus sign is expands a string):
let s = "number: " + num;
let s = 'number: ' + num;
ES6 template literals:
let s = `number: ${num}`
Get more information on these links:
JS Strings
Template literals
Related
I wrote a function constructor with a prototype that is creating svg picture and inserting it into the web page. I have 2 questions though:
1 Is it all right to take part of the code inside of constructor that is being used in the process of creating instance and move it to the prototype object. As far as I see these prototype methods are used generally with already created instances, for example var a = [2,3,4]; a.reverse()
2 Is it fine to manipulate DOM-objects that way inside of function constructor? DOM objects are not js native objects, they are host objects outside of js-engine.They are similar to js objects but created by browser somewhere else
Below is the code:
function Sektor(selector, options) {
// Find a DOM object representing the HTML element with the supplied selector
// create a property called element
// This DOM object is assigned to the element property
this.element = document.querySelector(selector);
// Some default values in case nothing is supplied
const defaultOptions = {
size: 100,
circleColor: '#b3c9e0'
};
// Merge options with default ones
options = Object.assign(defaultOptions, options);
// Circle dimensions
options.center = options.size / 2;
options.radius = options.center;
// create a property called options
this.options = options;
// Get SVG
const svg = this.getCircle();
// SVG is injected into the DOM element with JavaScript
this.element.innerHTML = svg;
}
// Assigning a method to the constructor's prototype
// This method generates SVG
Sektor.prototype.getCircle = function() {
const options = this.options;
return `
<svg class='Sektor' viewBox='0 0 ${options.size} ${options.size}'>
<circle class='Sektor-circle' fill=${options.circleColor} cx='${options.center}' cy='${options.center}' r='${options.radius}' />
</svg>
`;
};
var sektor = new Sektor( '.example-one', { circleColor: '#7da385' } );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Draw</title>
<style>
body {
margin: 0;
padding: 0;
}
.examples {
display: flex;
justify-content: space-between;
padding: 20px;
}
.example {
margin: 0px auto;
}
.Sektor {
width: 200px;
height: 200px;
background-color:#f2f2f2;
}
</style>
</head>
<body>
<div class='examples'>
<div class='example'>
<div class='example-one'></div>
</div>
</div>
<script src='sektor.js'></script>
</body>
</html>
I've seen similar questions asked before but none of them really helped in my situation. To boil it down I, a noobie, am trying to change an html background color to a variable that was created in a js script and I'm not sure quite how to do this. I want "color" to be used for the background color. h, m, s are hours minutes and seconds. I'm pulling these from the computer and it is working fine printing it. Here is something I found that is nearly identical to what I want to do www.jacopocolo.com/hexclock/
JS
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
$("div.background").css("background-color", color );
HTML
<style>
.background {
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
I've tried making a div for the background (shown above) but it doesn't seem to be working. In the end all I'm really set on is this part of it
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
Can someone tell me how to properly do this or even just point me in the general direction? Any help would be greatly appreciated.
I tried it, and it works fine.
$(document).ready(function(){
var h = 0;
var m = 9;
var s = 20;
if (h<=9) {h = '0'+h}
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
console.log('color' + color);
console.log("Original Color " + $("div.background").css('background-color'));
$("div.background").css("background-color", color );
console.log("Updated Color " + $("div.background").css('background-color'));
});
<html>
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
<style>
.background {
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="background">hello world</div>
</body>
</html>
The problem in your code is probably that a color parameter pre-pended with '#' must be given in hexadecimal coordinates:
red=10, green=20 and blue=40 should be written like this:
#0A1428
So, you have to convert first to hexadecimal each coordinate like this:
var h = h.toString(16);
var m = m.toString(16);
var s = s.toString(16);
Then, perform the zero left-padding, and so.
I added a CKFinder button on my website that calls this function on click:
<script type="text/javascript">
function BrowseServer(a)
{
var which=a;
var finder = new CKFinder() ;
finder.basePath = 'ckfinder/' ;
finder.selectActionFunction = SetFileField ;
finder.selectFunctionData = a ;
finder.popup() ;
}
function SetFileField( fileUrl, data )
{
document.getElementById(which).value = fileUrl ;
insertTextAtCursor(getObj('message'), fileUrl);
}
</script>
This opens up a blank window. When I view the source, this is what I see:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>CKFinder 2</title><style type="text/css">body, html, iframe, #ckfinder { margin: 0; padding: 0; border: 0; width: 100%; height: 100%; overflow: hidden; }</style></head><body></body></html>
I have enabled error_reporting in the ckfinder/config.php and connector file. Yet am not seeing any error.
Surprisingly, the ckfinder works with my ckeditor integration but doesnt work when called with Javascript from a button.
What may be the problem?
I'm having a problem getting my code to work when it's incororated into a live site. The fiddle works just fine, but when I include the identical code in a webpage, I can't get the function to load/work at all.
<!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>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Drag and Drop Assignment</title>
<!doctype html>
<link rel="stylesheet" href="styles/style1.css"/>
<style>
.drop{
float: left;
width: 350px;
height: 400px;
border: 3px solid blue;
background-image: url("http://debsiepalmer.com/images/tardis 2.jpg");
background-repeat: no-repeat;
background-size: cover;
}
#right{float: left;
width: 350px;
height: 400px;
border: 3px solid red;
}
</style>
<script src="draganddrop.js" ></script>
<script src="http://code.jquery.com/jquery-2.0.2.js" ></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" ></script>
<script type="text/javascript">
$ (init);
function image(id, image1) {
this.id = id;
this.image1 = image1;
}
$('#deal').click(function () {dealAll(
dealCard(randomCard()));
});
$(function() {
$( "#draggable" ).draggable({ containment: "#left"});
});
function init() {
$('.drop').droppable( {
drop: handleDropEvent
} );
$("img").draggable();
}
// global variables
var cardsInDeck = new Array();
var numberOfCardsInDeck = 15;
cardsInDeck[0] = "Ace";
cardsInDeck[1] = "Grace";
cardsInDeck[2] = "Susan";
cardsInDeck[3] = "Ian";
cardsInDeck[4] = "Barbara";
cardsInDeck[5] = "Brigadier";
cardsInDeck[6] = "Romana I";
cardsInDeck[7] = "K9";
cardsInDeck[8] = "Tegan";
cardsInDeck[9] = "Jamie";
cardsInDeck[10] = "Sarah Jane";
cardsInDeck[11] = "Jo";
cardsInDeck[12] = "Romana II";
cardsInDeck[13] = "Yates";
cardsInDeck[14] = "Leela";
var cardsDealt = new Array();
function dealAll(){
var z=0;
for (z=0;z<5;z++) {
cardsDealt[z] = new Image(z,dealCard(randomCard()));
}
}
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var $img = new Image();
$img.src = "images/Companions/" + cardsInDeck[i] + ".jpg";
// Here I set the ID of the object
$img.id=cardsInDeck[i];
$img.class='drag';
document.body.appendChild($img);
$('#'+$img.id).draggable();
removeCard(i);
return $img;
}
// deal randomly - works
function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);
}
function removeCard(c)
{
for (j=c; j <= numberOfCardsInDeck - 2; j++)
{
cardsInDeck[j] = cardsInDeck[j+1];
}
numberOfCardsInDeck--;
numberOfCardsInDeck--;
numberOfCardsInDeck--;
}
function handleDropEvent( event, ui ) {
alert("Fantastic! You chose " + ui.draggable.attr("id") + " to be your companion.");
// Here I want the id of the dropped object
}
</script>
</head>
<body>
<div id="container" div style="width:750px; margin:0 auto;">
<div id="page_content" style="left: 0px; top: 0px; width: 750px" class="auto-style8">
<!--Begin Assignment 10 --->
<div id="left" class="drop">
<img id="tardis" ></img>
</div>
<input type="button" value="Get Companions" id="deal" />
<div id="content" style="left: 0px; top: 0px; width: 750px">
</div>
</div>
</div>
</body>
</html>
It's supposed to generate 5 images, one of which can be selected to be dropped onto the target and generate an alert with the id of the image being dropped. Like I said, it works just fine in the fiddle - and the code is identical on the web page, so I don't understand what I'm doing wrong.
fiddle: http://jsfiddle.net/reaglin/FUvT8/6/
I ordered some code...and for me it worked
// global variables
var cardsInDeck = [],
numberOfCardsInDeck = 5;
cardsInDeck[0] = "Ace";
cardsInDeck[1] = "Grace";
cardsInDeck[2] = "Susan";
cardsInDeck[3] = "Ian";
cardsInDeck[4] = "Barbara";
cardsInDeck[5] = "Brigadier";
cardsInDeck[6] = "Romana I";
cardsInDeck[7] = "K9";
cardsInDeck[8] = "Tegan";
cardsInDeck[9] = "Jamie";
cardsInDeck[10] = "Sarah Jane";
cardsInDeck[11] = "Jo";
cardsInDeck[12] = "Romana II";
cardsInDeck[13] = "Yates";
cardsInDeck[14] = "Leela";
//load "init" when document it's ready
$(document).on('ready',init);
function init() {
$( "#draggable" ).draggable({ containment: "#left"});
$('.drop').droppable( {drop: handleDropEvent});
}
$('#deal').click(function () {
dealAll();
});
$('#reset-pictures').click(function(){
$('img.drag').remove();
numberOfCardsInDeck = 5;
});
// deal 5 cards at once - works
function dealAll(){
// 5 cards max, no repeat cards
while(numberOfCardsInDeck){
var rand = randomCard();
dealCard(rand);
}
}
//deal cards - works
function dealCard(i) {
//create id, remove space id
var id_picture = (cardsInDeck[i] +'-'+i).replace(/\s/g, '');
//validate not exist image
if (!!$('img#'+id_picture).length) {
return;
}
var $img = $('<img/>', { src : "http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg", id : id_picture, class : 'drag', 'data-info': cardsInDeck[i]
})
$('body').append($img);
$('img.drag').draggable();
numberOfCardsInDeck--;
}
// deal randomly - works
function randomCard() {
return Math.floor(Math.random() * cardsInDeck.length);
}
// this is what to do when card drops in tardis
function handleDropEvent( event, ui ) {
alert(ui.draggable.attr("data-info"));
}
DEMO
JSFinddle
Are you linking to JQuery correctly in the live version? Sometimes when moving from a development area to a live system the references mess up, you can find out if a reference is working or not by viewing the source code and entering in the link into the URL.
This is how you fix it: Take all the javascript (from $ (init) to the alert()) and place it at the bottom of the loaded page, inside the body, after all the elements. This ensures that the javascript knows what named elements you are talking about.
I would like to emphasise that this is not a tip for writing good javascript. The problem arises because it's bad javascript to begin with. Well written pages do not rely on the position of the code within the page, rather the opposite in fact.
Postscript: I literally did the following: I came here after googling "drag and drop"; I didn't fully read the actual question; I went to the jfiddle; I copied all the code for my own purposes; I couldn't get it to work; I fixed it (just trial and error really); I fixed the bug which is still present even on the jfiddle page; and then I came back here to find out what the original query had been!
The other bug is the fact that you can't drag the images of "Romana I", "Romana II" and "Sarah Jane". As the code makes the array values the id of the image elements, maybe others can instantly spot what causes that problem.
So I'm trying to do some very basic div re-sizing based on the properties of the image contained within it. I know I can do something really basic like set the background an padding around the image and achieve the same effect, but this is sort of a personal challenge.
The problem I am having is that when I try to fetch the naturalHeight or naturalWidth values of the image, I get a value of 0. However, when I try to fetch these values using the console, they return the correct values. Also, my resizeDiv() function is coming up as undefined in console.
Here's the code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>kitten_resize - WesGilleland.com</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var kittens = new Array("100x100_kitten.jpeg","150x150_kitten.jpeg","200x150_kitten.jpeg");
$('#kittens').attr('src', kittens[0]); //set the image
function resizeDiv() {
var img = document.getElementById('kittens');
var imgH = img.naturalHeight;
var imgW = img.naturalWidth;
$('div').width(imgW);
$('div').height(imgH);
console.log('Current imgH: '+imgH);
console.log('Current imgW: '+imgW);
};
resizeDiv();
});
</script>
<style>
div {
background-color: black;
padding: 10px;
margin: auto;
}
</style>
</head>
<body>
<div>
<img id="kittens" src='' />
</div>
</body>
</html>
You can also find a working copy here: http://www.wesgilleland.com/projects/kitten_resize/
I feel like it's something very basic that I'm missing; I haven't fiddled with this stuff since my associate's degree a year ago. Thanks to anyone who can help!
That's because your image isn't yet loaded when you read the original dimensions.
You should read the dimensions when the image is loaded :
var img = $('#kittens')[0];
img.onload = resizeDiv;
img.src = kittens[0];