How to dynamically create svg element and animate a image - javascript

I have a requirement on page load I need to create an 'Image' attribute and append it to the svg element to start animation. However, I tried to create Image and associated animate element and attach it to the svg element.The image is getting displayed on the page however it is not getting animated.
Can any one pls help in this.
code added at
http://jsbin.com/dofun/1/edit?html,js,output
Thanks
Pavan Kumar

Setting a duration for an animation is mandatory. If you add
animate.setAttribute('dur', '3s');
it animates correctly for me provided I add an svg element with an appropriate id.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<svg width="100%" height="100%" id="svg_image"/>
</body>
</html>
body, html {
width : 100%;
height: 100%;
}
var img = document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttributeNS(null,'height','536');
img.setAttributeNS(null,'width','536');
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg');
img.setAttributeNS(null,'x','10');
img.setAttributeNS(null,'y','10');
img.setAttributeNS(null, 'visibility', 'visible');
img.setAttributeNS(null,'id','image_test');
// animate object
var animate = document.createElementNS('http://www.w3.org/2000/svg','animate');
animate.setAttributeNS(null,'attributeName','x');
animate.setAttributeNS(null,'from',500);
animate.setAttributeNS(null,'to',0);
animate.setAttribute('dur', '3s');
//append animate with image
img.appendChild(animate);
document.getElementById("svg_image").appendChild(img);

Related

Repeatedly Toggle Div Background Color On Click Using Inline Vanilla JavaScript on a Webpage

*To the reader looking from help: Each of the first 4 solutions worked for me, and the suggested question shows potential. I picked Hunsnul Amand's code because it allows for easy expansion of colors in a JavaScript string, and toggles through all three colors mentioned in the problem below. I like the way this sets up the possibility of additional or random colors later. The other three solutions on this page rely on various snippets of JavaScript toggling between additional classes made in CSS. Ranjeep and Keith's snippets use this in very simple and clean code that's easy to follow. Jateen makes use of the .toggle and ++> elements, which are useful as well. His code was also easy to follow. *
Thank You for checking this out. I'm trying to do something that seems like a very basic skill, but am having trouble finding the specific syntax or code that will cause a webpage to repeatedly toggle the background color of a circular div on a click rather than on a button using Vanilla JavaScript. I've tried too many iterations to post here, and received various effects from trying to modify similar projects to my needs, but haven't been able to get the div's background color to toggle.
background: I started with a sample project that lets you cause a div shaped in a circle with a red background to disappear by setting the background color to "none." I'd like to change the code to something that will instead allow a repeated toggle of the circular div's background color between either red to blue, or at least from red to none and back again.
<!-- This document should let you toggle a circle's color between
red and blue using vanilla JavaScript, HTML, and CSS.
The circle is an HTML div shaped and colored in CSS,
and given the toggle function that changes the div's color
in JavaScript.
Biggest need: A JavaScript toggle funciton that alternates
the color of a div when the user clicks on the div.-->
Mini Challenge: Disappearing Circles
minichallenge.html!
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#circle {
width:200px;
height:200px;
border-radius:100px;
background-color:red;
}
</style>
</head>
<body>
<div id="circle"></div>
<script type="text/javascript">
/*original JavaScript Project*/
document.getElementById("circle").onclick=function() {
document.getElementById("circle").style.display="none";
}
/* New JS: Purpose: A JavaScript toggle funciton that alternates
the color of a div when the user clicks on the div.-
var userClick = document.getElementById("circle").onclick=function() {
var noDiv = document.getElementById("circle").style.display="blue";
var redDiv = document.getElementById("circle").style.display="red";
-Pseudocode-:
if userClick
noDiv
else redDiv; */
</script>
</body>
</html>
Thanks Again.
Here is one of many solutions. In your script try this.
let i = 0;
const colors = ["blue", "red", "transparent"];
document.getElementById("circle").onclick = function () {
document.getElementById("circle").style.backgroundColor = colors[i];
i++;
if (i == colors.length) i = 0;
};
This way you can add as many colors as want to the colors array and it will work.
You can create a .bg-none class in you css. Then toggle that class onclick of the element. I have updated the code, please chekc
<style>
.bg-none{
background-color: transparent !important;
}
</style>
<script>
document.getElementById("circle").onclick=function() {
document.getElementById("circle").classList.toggle("bg-none");
}
</script>
Using CSS here, and the classList toggle method is the simplest way.
eg.
document.getElementById("circle").onclick=function() {
document.getElementById("circle").classList.toggle('toggle');
}
#circle {
width:200px;
height:200px;
border-radius:100px;
background-color:red;
}
#circle.toggle {
background-color:blue;
}
<div id="circle"></div>
I have moved your background-color CSS to 2 new classes, which would toggle as you click on the div. I hope this resolved your query.
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#circle {
width:200px;
height:200px;
border-radius:100px;
}
.bg-red {
background-color: red;
}
.bg-blue {
background-color: blue;
}
</style>
</head>
<body>
<div id="circle" class="bg-red"></div>
<script type="text/javascript">
const circleDiv = document.getElementById("circle");
circleDiv.addEventListener('click', () => {
circleDiv.classList.toggle('bg-red');
circleDiv.classList.toggle('bg-blue');
});
</script>
</body>
</html>

Cannot read property 'value' of null at index.html:15 in color

<html>
<head>
<title>Website</title>
</head>
<style>
#square{
width: 50;
height: 50;
background-color: red;
}
</style>
<body id="body">
<script>
var picker = document.getElementById("square")
var color = document.getElementById("colorBox").value
function onClick(){
document.getElementById("body").style.backgroundColor = color
}
</script>
<input type="color" id="colorBox"/><br />
<button onclick="onClick();">Change</button>
<div id="square"></div>
</body>
It produces the error which is the title.
There is no issues with layout. Just the 15 lines.
Look, I don't know what to put here.
It's because your element with ID colorBox is defined after the script. This means that when the script runs, it cannot find the element. If you move the script tag below your element definition, your code will run properly.
Note, I think another issue with your code is that you compute the value of color before your onClick function, so it will always set the background color to black when you click the button. If you move the color definition to inside of the function, it will be recomputed every time you click the button, giving what I believe is the desired result:
<html>
<head>
<title>Website</title>
</head>
<style>
#square {
width: 50;
height: 50;
background-color: red;
}
</style>
<body id="body">
<input type="color" id="colorBox" /><br />
<button onclick="onClick();">Change</button>
<div id="square"></div>
<script>
var picker = document.getElementById("square")
function onClick() {
var color = document.getElementById("colorBox").value
document.getElementById("body").style.backgroundColor = color
}
</script>
</body>
Your script is scanning the document for your colorbox element before it has encountered that HTML. Move the script to just before the closing body to only run it after all the HTML has been parsed.
And while this will solve your most immediate problem, you'll find that there are still other problems, so see my second example for that solution.
<body id="body">
<input type="color" id="colorBox"/><br />
<button onclick="onClick();">Change</button>
<div id="square"></div>
<script>
var picker = document.getElementById("square")
var color = document.getElementById("colorBox").value
function onClick(){
document.getElementById("body").style.backgroundColor = color
}
</script>
</body>
Now, with that fixed, there are several other items that need attention:
Nothing is allowed to go after the closing head tag and before the
opening body tag. The style element should go inside of the
head.
In CSS, most of the time you must place a unit of measurement after
an amount, so your height and width of 50 won't work unless you add
something like px, %, em, etc.
Don't set your variables equal to properties of elements. Set
variables to the elements themselves. Your code gets the value of
the input before the user has selected a color, you need to set
the color after they've chosen. By only getting the element reference
up front, you can then easily get the current value of that element
at just the time you need it.
There is no need to give body an id so that you can reference it
later. A document will only ever have one body and it is accessible
via document.body.
Don't use HTML event attributes (like onclick) to set up your
events. Instead, do your event handling separately, in JavaScript.
Don't use self-terminating XHTML syntax. It buys you nothing and
opens the door to bugs.
Lastly, get your element references just once, not inside of your
event handler because every time that function runs, it will scan the
document again for the same element it already found earlier.
So here's your code again, with these tips applied:
<!doctype html>
<html>
<head>
<title>Website</title>
<style>
#square{
width: 50px; /* In CSS, you must also put a unit next to an amount */
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<input type="color" id="colorBox"><br>
<button>Change</button>
<div id="square"></div>
<script>
// Get your element references, don't get references to element properties
var body = document.body;
var picker = document.getElementById("square");
var color = document.getElementById("colorBox");
// Set up your event handlers in JavaScript, not HTML
document.querySelector("button").addEventListener("click", onClick);
function onClick(){
// Set the color of the body to the current value of the input
body.style.backgroundColor = color.value;
}
</script>
</body>
</html>

JavaScript changing images with onmouseover and onmouseout

I've looked at similar questions and answers on Stack Overflow which I can't get to work. everything is find when the page loads but when I mouse over it doesn't show the new gif.
When inspecting the code in the browser it seems to be switching between the two images.
<!DOCTYPE html>
<html>
<head>
<script>
function normalImg() {
document.getElementById("smile").src = "/smiley.gif"
}
function singing() {
document.getElementById("smile").src = "/sing.gif"
}
</script>
</head>
<body>
<img onmouseout="normalImg()" border="0" src="smiley.gif" alt="Smiley" width="32" height="32" id="smile"
onmouseover="singing()" border="0" src="sing.gif" alt="singing" width="32" height="32">
<p>onmouse out and onmouseover changing images</p>
</body>
</html>
you should have only one src attribute inside < img /> tag, you could try the code below:
<!DOCTYPE html>
<html>
<head>
<script>
function singing() {
document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/0/06/180717_%EC%97%B4%EB%A6%B0%EC%9D%8C%EC%95%85%ED%9A%8C_%ED%8A%B8%EC%99%80%EC%9D%B4%EC%8A%A4_%2818%29.jpg"
document.getElementById("smile").alt="smiling"
}
function crying() {
document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png"
document.getElementById("smile").alt="crying"
}
</script>
</head>
<body>
<img onmouseover="singing()" onmouseout="crying()" src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png" alt="singing" width="100" height="100" id="smile">
<p>onmouse out and onmouseover changing images</p>
</body>
</html>
You don't need the / at the start of your path to gif.
Replace
document.getElementById("smile").src = "/smiley.gif"
with
document.getElementById("smile").src = "smiley.gif"
Same for the sing.gif
Instead of using javascript to change image source on mouseout and mouseover, it will be better to change image source on based on just hover.
Check this out:
CSS: Change image src on img:hover
Hover handles both a mouseenter event and a mouseleave event.
Mouseover is best for situations where you only care when the mouse has crossed the border into an element and you don't really care what happens if it leaves. If you want to trigger some event on the element.

I'm having an issue where the 'mouseover' event is simply starting before I even mouseover the selected element

As soon as I load or reload the page. The gif i've included in the html starts playing.
$('.text').mouseover(function() {
$('.hover').css("visibility", "visible"); })
$('.text').mouseout(function() {
$('.hover').css("visibility", "hidden"); });
I want the gif to start whenever I hover over the relevant element and stop when I take my cursor off. This JS is in a script tag within the body of HTML doc. It works after I hover over the 'text' element for the first time. Would love some guidance on what I am doing wrong.
It's likely that the visibility of the image is visible on the initial page load. When you do your first mouseover, then mouseout, it gets set to hidden, which is your expected behavior. Try setting the visibility of the img to hidden, by one of these methods:
Add a style in the head of the page:
<html>
<head>
<style>
img.hover { visibility: hidden; }
</style>
</head>
<body>
<img src='path/to/image.gif' class='hover' />
</body>
</html>
Or, set the style inline in the image itself:
<html>
<body>
<img src='path/to/image.gif' class='hover' style='visibility: hidden' />
</body>
</html>

jquery cycle curtainX not working properly

I'm having a problem with my 'curtainX' cycle animation in jquery. The first animation seems to zoom out in the top center, instead of doing the animation it should. I can't seem to find the problem and now I don't know where to start. I tried checking the different options for the animations and can't seem to figure it out.
<!DOCTYPE html>
<html>
<head>
<style type = "text/css">img{position:absolute;}</style>
<script src = "jquery.js"></script>
<script src = "jquery-ui.js"></script>
<script src = "jquery-cycle.js"></script>
<script src = "text/javascript">
function start(){
$("#blank").cycle({
fx: 'curtainX',
sync: false,
delay: -4000
});
}
</script>
</head>
<body>
<div id = "blank" onclick = "start()">
<img src = "img/blank.gif" style = "z-index:1"/>
<img src = "img/1c.gif"/>
</div>
</body>
</html>
You can view a demo at http://vrbj.webs.com/flipTest.html
It seems to be a problem related to the absence of a width and a height.
I've rewritten the code here
Removing width and height causes your problem.
You can solve changing:
img{position:absolute;}
to
img{position:absolute; width: 59px; height: 74px;}
Consider also the way you have written your code, taking a loo at what i've written.
Your code's right but the way is written is less "plugin's compliant" than in the fiddle.
Functions in the tag are called when they are needed. Try moving your start function within the tag and put that within an $(document).ready( your function ) call

Categories