How can I reference a variable from a js script in html - javascript

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.

Related

Set backgroundImage in HTML with URL pulled from JSON data

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

How to explain these lines of JavaScript?

Both light and order are arrays containing states with the period of time they are displayed.
However I'm not too sure about what Index does or 'sId'. could someone please explain these? The code changes the sequence of a traffic light. The code works however I wanted to know what lightIndex does, as when I change it it doesn't work.
<!DOCTYPE html>
<html>
<style type="text/css">
.light {
height: 30px;
width: 30px;
border-style: solid;
border-width: 2px;
border-radius: 25px;
}
.lightRed {
background-color: red;
}
.lightYellow {
background-color: yellow;
}
.lightGreen {
background-color: green;
}
</style>
<body>
<div id="trafficLight">
<div>Click to Start and Stop</div>
<div class="light" id="Red"></div>
<div class="light" id="Yellow"></div>
<div class="light" id="Green"></div>
</div>
<button type="button" onclick="changeState()">Change Lights</button>
<button type="button" onclick="changeState()">automatic</button>
<script>
var changeState = (function () {
var state = 0,
lights = ["Red", "Yellow", "Green"],
lightsLength = lights.length,
order = [
[7000, "Red"],
[2000, "Red", "Yellow"],
[7000, "Green"],
[2000, "Yellow"]
],
orderLength = order.length,
lightIndex,
orderIndex,
sId;
return function (stop) {
if (stop) {
clearTimeout(sId);
return;
}
var light,
lampDOM;
for (lightIndex = 0; lightIndex < lightsLength; lightIndex += 1) {
light = lights[lightIndex];
lightDOM = document.getElementById(light);
if (order[state].indexOf(light) !== -1) {
lightDOM.classList.add("light" + light);
} else {
lightDOM.classList.remove("light" + light);
}
}
sId = setTimeout(changeState, order[state][0]);
state += 1;
if (state >= orderLength) {
state = 0;
}
};
}());
document.querySelector('change Lights', 'automatic').addEventListener("click", (function () {
var state = false;
return function () {
changeState(state);
state = !state;
};
}()), false);
</script>
</body>
</html>
lightIndex and sId are both just variable names created by whoever wrote the code. They don't 'mean' anything inherently -- the creator of the code could have chosen whatever variable names they wanted. However, in your code, both of these variables have uses that are fairly self-evident from their names.
lightIndex is an integer (between 0 and 2), which is used as an index of the array lights, so that the current light (light) can access the relevant colour with light = lights[lightIndex];. Presumably lights is set up like var lights = ['green', 'orange', 'red']. So, for example, light = lights[lightIndex] becomes light = lights[1], making light become equivalent to orange.
sId is a time-delayed function (setTimeout(changeState, order[state][0]);). setTimeout() takes two parameters -- a function to execute, and a time delay in milliseconds. In this example, order[state][0] will be equivalent to something like 1000 (one second), and changeState() is the function to execute. Essentially, every one second, change the state of the light (to a different colour).
I don't know why you'd try to change lightIndex, but if you want to reverse the direction of the lights changing, you need to reverse the for loop:
for (lightIndex = 0; lightIndex < lightsLength; lightIndex += 1) {
Becomes:
for (lightIndex = lightsLength; lightIndex > 0; lightIndex -= 1) {
If you want to change the speed, you need to change order[state][0]. As you don't show the order variable's code, you'll need to work out how to change that yourself.
Hope this helps!

How do I insert a node in a graph in sigmajs while inside angularjs

Note: I just vastly simplified the program and have left it with the bare essentials ...
So I am trying to add graphs within a sigma.js graph. First, let me post the javascript (sigmaAngualr.js) ...
app = angular.module('sigmaAngular', []);
app.controller('NetworkDataCtrl', function($scope){
var i, s;
$scope.newName = null;
$scope.s = null;
$scope.N = 3;
$scope.newNode = function (id, label){
return {id: id,
label: label,
x: Math.random(),
y: Math.random(),
size: Math.random()+0.2,
color:'#333'}
};
$scope.addNodeGraph = function(id, label){
$scope.s.graph.addNode($scope.newNode(id, label));
console.log(id+'-'+label);
};
$scope.tempNodes = [];
for( i=0; i<$scope.N; i++ )
$scope.tempNodes.push($scope.newNode('id'+i, 'Node'+i));
$scope.s = new sigma({graph:{nodes:$scope.tempNodes, edges:[]}})
});
app.directive('showGraph', function(){
// Create a link function
function linkFunction(scope, element, attrs){
scope.s.addRenderer({container: element[0]})
};
return {
scope: false,
link: linkFunction
}
});
And here is the HTML ...
<!DOCTYPE html>
<html>
<head>
<title>Using AngularJS</title>
<script type="text/javascript" src='lib/sigma/sigma.min.js'></script>
<script type="text/javascript" src='lib/angular/angular.min.js'></script>
<script type="text/javascript" src='lib/sigmaAngular.js'></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body ng-app='sigmaAngular'>
<div>
<div ng-controller='NetworkDataCtrl'>
<input type='text' ng-model='newName' />
<button ng-click='addNodeGraph(newName,newName)'> Add Node </button>
<hr>
<div show-graph id='graph-container' s='s' tempNodes='tempNodes'>
</div>
<hr>
</div>
</div>
</body>
</html>
Of course, I am unable to add a node to the graph.
I had also tried another option of creating an entire graph when I add a node. That doesnt work either. (This is no longer true)
Let me try to explain. Now,
When I refresh the browser, I do not see a graph.
When I resize the browser window The graph suddenly appears.
When I type a random name and hit the Add Node button, the graph doesnt change.
When I resize the browser window, the graph changes to reveal the new node.
So in summary, I have to resize the browser window to see any changes in the graph.
Just a side note: The css is below:
#graph-container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid indianred;
}
I feel now that I am really close to solving the problem. Just a tiny bit off somewhere ...
Any help will be greatly appreciated!!!

Drag and Drop Jquery function not working in site

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.

Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery?

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];

Categories

Resources