How to change id on canvas - javascript

I have a page that displays a gif icon based on a string on a canvas. For example "clear-day". It is possible to fetch that string from an api. My question is how i assign the variable "icon" that includes that string to the id of my canvas. Of course there are better ways of doing this as i´m a beginner.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Animated weather icons</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<figure class="icons">
<canvas class="weatherIcon" width="64" height="64"></canvas>
</figure>
<script src="https://rawgithub.com/darkskyapp/skycons/master/skycons.js"></script>
<script>
$(document).ready(function weather(){
$.getJSON("https://api.darksky.net/forecast/[key]/59.868098,%2017.678976?lang=sv&callback=?",
function(json) {
var weatherJSON = json.currently;
var icon=weatherJSON.icon;
var icons = new Skycons({"color": "white"});
icons.set("clear-day", Skycons.CLEAR_DAY);
icons.set("clear-night", Skycons.CLEAR_NIGHT);
icons.set("partly-cloudy-day", Skycons.PARTLY_CLOUDY_DAY);
icons.set("partly-cloudy-night", Skycons.PARTLY_CLOUDY_NIGHT);
icons.set("cloudy", Skycons.CLOUDY);
icons.set("rain", Skycons.RAIN);
icons.set("sleet", Skycons.SLEET);
icons.set("snow", Skycons.SNOW);
icons.set("wind", Skycons.WIND);
icons.set("fog", Skycons.FOG);
var iconWeather = document.getElementsByClassName("weatherIcon");
iconWeather.id = icon;
icons.play();
});
});
</script>
</body>
</html>

Try:
document.getElementsByTagName("canvas")[0].setAttribute("id", icon);

To achieve expected result, use below option
Document.getElementByClassName returns an array-like object of all child elements which have all of the given class names.
Change iconWeather.id = icon; to iconWeather[0].setAttribute("id", icon);

Related

how to randomize image once it is clicked?

I am trying to create a random gif generator. Very simple in design, just have the gif/img load in and once the user clicks/taps it randomizes and pulls another random image from the array.
For now I would just like to have the image randomize when it is clicked.
Currently it only randomizes when the page is refreshed.
HTML
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/rand.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<head>
<title>Gif Generator - Prototype</title>
</head>
<body>
<h1>Gif Generator - Prototype</h1>
<section>
<p>This image is random</p>
<a href="#" class="click">
<script>
getRandomImage()
</script>
</a>
</section>
</body>
JS
var randomImage = new Array();
randomImage[0] = "images/100.jpg";
randomImage[1] = "images/200.jpg";
randomImage[2] = "images/300.jpg";
randomImage[3] = "images/400.jpg";
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
As per your jQuery reference at the top, below is the proposed solution:
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomImage.length);
$(this).html('<img src="'+randomImage[number]+'" />');
});
});
on click method serves the purpose.
in an <img> tag you can add an onclick method
<img src="" alt="Random image" onclick="getRandomImage()">

Simple javascript change image not working

I want to change an image's src on click of a link. I got a javascript snippet and tried to integrate it but it doesn't work.Im
Here's my HTML:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="styles/script.js"></script>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
</body>
</html>
Here is my script.js:
var imageId = document.getElementById("bgimage");
function changeImage() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
This issue is occurring because the script appears in the html before the <img> element. Therefore, the code tries to find the img element, but it can't because the js code executes before the rest of the html is parsed. Correct it by putting the js include tag just before </body>:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
<script src="styles/script.js"></script>
</body>
</html>
Or, you might want to use DOMContentLoaded to wait until the html has been parsed. Change the js to this, in that case:
var changeImage;
document.addEventListener('DOMContentLoaded',function(){
var imageId = document.getElementById("bgimage");
changeImage=function() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
},false);
Or you could call document.getElementById() every time changeImage is called
You must place your script just before </body>, or run it at onload.
If not, you run
var imageId = document.getElementById("bgimage");
before loading the image to the DOM, so imageId is null.
Anyway, you could improve your function to
var images = ["images/1.jpg", "images/2.jpg" /*, ... */];
function changeImage() {
imageId.src = images[(images.indexOf(imageId.src)+1) % images.length];
}

Get iframe with window.frames property vs. iframe ID

I wonder why the following doesn't work:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe name="myFrame"></iframe>
<script>
window.frames["myFrame"].style.background = "green";
</script>
</body>
</html>
However, if you access the iframe directly using its ID, it works with no problem:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe id="myFrame"></iframe>
<script>
document.getElementById("myFrame").style.background = "green";
</script>
</body>
</html>
How can I use window.frames to get the first code to run properly?
I think you have to do a for loop to find all the frames and then access them by their index.
for(var i=0; i < frames.length; i++) {
console.log(frames[i]);
}
This doesn't work for you, because it will return the window object inside of the frame and not the iframe element. If you want to use the name attribute you can use document.getElementsByName("myFrame")[0] but I'd recommend accessing it by id.
It should work the same for getElementsByName, mind you that it returns an array of element, not an element.
Both statements should have the same effect for frame with name of "myFrame", and id of "myFrame":
document.getElementsByName("myFrame")[0].style.background = "green";
document.getElementById("myFrame").style.background = "green";

Javascript - Changing an image with variables

I'm trying to create a slide show but I'm having some difficulty. I've googled the problem and read loads of pages but I still can't get it to work. I'm doing this all in my header, then the header.php will be included on whichever page. I've tried setting the source to a string containing the location, creating an image before and then setting it to that image's source, and just trying odd things trying to get it to work.
The strange thing is when I call the updateSlider() function, the source of my image is null even though I can see it on the screen, and afterwards when I set it, it says there is a source but the image is the same.
But at the moment I'm just trying to change the image when I click a button and then I'm going to try and make the slide show. Here is the header.php code, you can see some of the different things I've tried in it:
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="all">#import "./includes/layout.css";</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var slideImages = new Array("includes/images/mmSlideImage1.png",
"includes/images/mmSlideImage2.png", "includes/images/mmSlideImage3.png");
var slideImage = newImage();
slideImage.src = slideImages[0];
pic = document.createElement("img");
pic.setAttribute("src", "includes/images/mmSlideImage2.png");
pic.setAttribute("alt", "No Image");
var url2 = "includes/images/mmSlideImage2.png";
var img2 = new Image();
img2.src = url2;
function updateSlider() {
console.log(document.getElementById("ht").getAttribute("src"));
document.getElementById("ht").setAttribute("src", img2.src);
console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<img src="includes/images/mmSlideImage1.png" alt="Logo" width="970" height="278" />
<button type="button" onclick="updateSlider()">Update Slider</button>
<div id="nav">
Home
About
Gallery
Programs
</div>
Thank you in advance for any help!
==================================================================================
UPDATED CODE:
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="all">#import "./includes/layout.css";</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"
</script>
<script>
var url2 = "includes/images/mmSlideImage2.png";
function updateSlider() {
console.log(document.getElementById("ht").getAttribute("src"));
$('ht').attr('src', url2);
console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<img src="includes/images/mmSlideImage1.png" alt="Logo" width="970" height="278" />
<button type="button" onclick="updateSlider()">Update Slider</button>
Simple. You're trying to give an anchor a image attribute. Give your img an id and fix it in the Javascript. For example, if you give it an "currentSlideImage" id:
$('#currentSlideImage').attr('src', url2);
BTW, I'd suggest you take a read on Unobstrusive Javascript.
i am not sure why are you using new image when you are just changing src of an image tag.
the easiest way is to use jquery code
$('#imgTagID').attr('src', url2);
or in javascript
document.getElementById("imgTagID").src = url2;
Here you go you were just missing id Tag inside jquery i just tried it with online images
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var url2 = "http://www.thinkstockphotos.com.au/CMS/StaticContent/WhyThinkstockImages/Best_Images.jpg";
function updateSlider() {
//console.log(document.getElementById("ht").getAttribute("src"));
$('#ht').attr('src', url2);
//console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<a href="index.html" class="logo" > <img id="ht" src="http://www.nasa.gov/sites/default/files/images/743348main_Timelapse_Sun_4k.jpg" alt="Logo" width="970" height="278" /></a>
<button type="button" onclick="updateSlider()">Update Slider</button>
</body>
</html>

pass CSS .class as a parameter to javascript function

the goal here is onclick of 1.gif, everything with .panel1 class disappears(style.display.none), and everything with a .panel2 class becomes visable (style.display.inline)
I'm new at this..so I think its just a syntax issue with ' ' or maybe " "
<!DOCTYPE html>
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
document.getElementByClass(panelIn).style.display="inline";
document.getElementByClass(panelOut).style.display="none";
}
</script>
</head>
<body>
<img class="panel1" src=1.gif onclick="panelTransition(panel1,panel2)" />
<img class="panel2" src=2.gif />
</body>
</html>
There is no getElementByClass. It's getElementsByClassName, and it returns an array of items, so you'll need to modify your code to loop through them.
function panelTransition(panelOut, panelIn) {
var inPanels = document.getElementsByClassName(panelIn);
for (var i = 0; i < inPanels.length; i++) {
inPanels[i].style.display = 'inline';
}
var outPanels = document.getElementsByClassName(panelOut);
for (var i = 0; i < outPanels.length; i++) {
outPanels[i].style.display = 'none';
}
}
If you were using a JavaScript library, like jQuery, this would be much easier to do. Also, as has been mentioned, you need quotes around your arguments to panelTransition.
<img class="panel1" src=1.gif onclick="panelTransition('panel1', 'panel2')" />
<img class="panel2" src=2.gif />
<img class="panel1" src=1.gif onclick="panelTransition('panel1','panel2')" />
I think you need quotes there
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
// panelIn gets turned on
setDisplay(panelIn,"inline");
// panelOut gets turned off
setDisplay(panelOut,"none");
}
function setDisplay(className,displayState)
{
// retrieve a list of all the matching elements
var list = document.getElementsByClassName(className);
// step through the list
for(i=0; i<list.length; i++) {
// for each element, set the display property
list[i].style.display = displayState;
}
}
</script>
</head>
<body>
<img class="panel1" src="1.gif" onclick="panelTransition('panel1','panel2')" />
<img class="panel2" src="2.gif" onclick="panelTransition('panel2','panel1')" />
</body>
</html>
Or you can accomplish the same in jQuery
// fires when the page is up and running
$(document).ready(function(){
// find all the panel1 elements,
// attach an on click handler
$(".panel1").bind("click", function(){
// find all the panel1 elements
// set their css display property to inline
$(".panel1").css("display","inline");
// find all the panel2 elements
// set their css display property to none
$(".panel2").css("display","none");
});
$(".panel2").bind("click", function(){
$(".panel2").css("display","inline");
$(".panel1").css("display","none");
});
});
You can learn all about jQuery here : http://www.jquery.com/
You'll only be able to get your code to run once, as soon as you click a panel1 image all of the panel2 images will disappear, you won't be able to click them back on ever again.

Categories

Resources