I´m developing a Javascript game and I have to place random coins in the HTML document. I have used this code so far:
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
}
This code simply places an image coin in the coordinates (0,0) of the document. What I want to do is access that recently created "div" and give it a random coordinate that I generate in another function so if I call several times the createCoin it creates several coins in the document. I can't use jQuery. Any ideas?
after create div element with id='coin' , to give the random position to div, use this:
<div id="coin" style="position:absolute">coin image</div>
<script language="javascript" type="text/javascript">
function newPos(){
var x=Math.random()*1000;
x=Math.round(x);
var y=Math.random()*500;
y=Math.round(y);
document.getElementById("coin").style.left=x+'px';
document.getElementById("coin").style.top=y+'px';
}
newPos();
</script>
we consider that createCoin() function execute once, on the onload() event. and then the newPos() function must be run.
Have createCoin return the div and then use it.
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
section.style.position = 'absolute';
section.style.left = '0px'; // units ('px') are unnecessary for 0 but added for clarification
section.style.top = '0px';
return section;
}
e.g.: var coin = createCoin(); coin.style.left = ???; coin.style.top = ???;
Related
So, I can get it to go from red to amber, but I am stuck on how to further get it to change to green, back to amber and then red again. Any help would be highly appreciated.
Also, I have created this on dreamwaver.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" onClick="changeLights()">Change Lights</button>
<script>
function changeLights(){
document.getElementById('light').setAttribute("src","../../amber.jpg")
document.getElementById('light').setAttribute("src","../../green.jpg")
document.getElementById('light').setAttribute("src","../../amber.jpg")
//document.getElementById('light').setAttribute("src","../../red.jpg")
}
</script>
</body>
</html>
The best solution is to put the image names into an array and the cycle through the array using a counter. That counter can increase or decrease the count depending on which "end" of the array we've last hit.
Also, don't use inline HTML event handling attributes (onclick, etc.) as they create "spaghetti code", they cause global wrapper functions that alter the this binding and they don't follow the W3C Event Model standard. Instead wire elements them up to event handlers via code using .addEventListener().
// Get references to DOM elements:
var img = document.getElementById('light');
var btn = document.getElementById('btn');
// Hook click of button up to event handling function
btn.addEventListener("click", changeLights);
// Put image names into an array:
var imgs = ["green.jpg" , "amber.jpg", "red.jpg"];
// Establish counter variable and directional variable
var count = 0;
var additive = 1;
function changeLights(){
// Set image by getting element from array based on current counter value
img.setAttribute("src","../../" + imgs[count]);
// Verification of action
console.clear();
console.log(img);
// When we hit the edges, reverse direction,
if(count === 2) {
additive = -1; // Go backward
} else if(count === 0) {
additive = 1; // Go forward
}
// Adjust the count accordingly
count+= additive;
}
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" id='btn'>Change Lights</button>
Below is my code for a simple text based game that i am trying to make but i cannot understand why the first time i call my function with a hyperlink 'link1', it works but when i add another link to my html document using javascript, and try to call another function onclick upon that link, it doesn't work. can somebody explain?
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
}
var link2event = document.getElementById("defend");
link2event.onclick = defend;
function defend() {
alert("working now");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="console">
<p id="startGameMessage"></p>
<div id="gameArea">
<p id="gameMessage">Some Text</p>
link1
<div id="placeHolder"></div>
</div>
</div>
When you link up your attack onclick, the element exists. But because #defend does not exist on the dom when you run var link2event = document.getElementById("defend");, your onclick never gets set.
Instead try:
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;
}
function defend(){
alert("working now");
}
jsfiddle https://jsfiddle.net/fv9mpbm6/
This will get your code working how you wish. If you don't do so, your code cannot work because the two lines added to the attack() function will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find anything, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
But do note that if you click attack more than once, your code will break because there will be more than one defend element.
When creating dynamic content, never use ids for handlers! Use classes instead
function attack() {
$('link2').insertBefore("#placeHolder");
}
Also, to ensure proper handling for elements that may not exist yet, leverage jquery's on functionality
$('body').on('click', '.defend', function() {
alert("working now")
})
it is simple, just put the two lines of code
var link2event = document.getElementById("defend");
link2event.onclick= defend;
inside the attack() function, at the end,and it works. This is the new attack() function:
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;}
If you don't do so this code cannot works because these two lines will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find nothing, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
I hope that this helps!
Cheers!
Try this, I am not sure is this what you expect
var getupvar = document.getElementById("attack"), i=0;
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend"+i);
link2event.onclick = defend;
i++;
}
function defend() {
alert("working now");
}
How do I flow a text stream from one div to the next? Each div has a fixed height and width and I need the data to be passed to the first, then if that is filled overflow to another etc. (The second etc. divs need to be dynamically created). Eventually the divs will be contenteditable, this is the page technique for a simple WYSIWYG style editor.
Please help...
JS Fiddle (note zoom in use on body)(I need to reflow on keyup/down, make pages and remove as necessary and be able to add in the middle)
function loadgo(){
run();
var h = document.getElementById('page'+(document.getElementById("pagecount").value-1)).offsetHeight;
document.getElementById("loadgo").value = h+1;
if (h > 1135){
var pagecount = document.getElementById("pagecount").value;
//$('body').append("<div class=page style='color:#F00' id='page"+pagecount+"' contenteditable>"+this.id+"</div>");
var objTo = document.body;
var divtest = document.createElement("div");
divtest.style.color = '#F00';
divtest.id = "page"+pagecount;
divtest.className = 'page';
divtest.contentEditable = "true";
divtest.innerHTML = "new div";
objTo.appendChild(divtest);
document.getElementById("page"+pagecount).focus();
document.getElementById("pagecount").value++;
zoomin();zoomout();
run();
}
}
function run(){
setTimeout(function() {
loadgo();
}, 500);
}
loadgo();
What you're looking for is called CSS Regions. This allows your text to flow through various containers placed on your site.
You can read about it on Adobe's site, and Apple has a nice WWDC video explaining how to implement it (starts at 8:40). Also check out the Editor's Draft.
I have made a simple zoom in and out function with button as well as mousewheel function. The main concept is to limit the maximum zoom level and minimum zoom level.
I have successfully made it in two ways
BIN 1
BIN 2
But i tried to make this in a tab section with unique ID or by class.
My script
var zoomLevel = 100;
var maxZoomLevel = 150;
var minZoomLevel = 50;
var initW=0,initH=0;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel+=10;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel-=10;
}else{
return;
}
}
img.style.width = (initW*zoomLevel/100)+"px";
img.style.height = (initH*zoomLevel/100)+"px";
img.style.marginLeft = ((initW-img.width)/2) + "px";
img.style.marginTop = ((initH-img.height)/2) + "px";
}
window.onload=function(){
var img=document.getElementById("pic");
initW=img.width;
initH=img.height;
img.onmousewheel=function(e){
e=e||window.event;
if(e.wheelDelta>=120) zoom(1.1);
else zoom(0.9);
};
if(/Firefox/.test(navigator.userAgent)){
img.addEventListener("DOMMouseScroll",function(e){
if(e.detail<0) zoom(1.1);
else if(e.detail>0) zoom(0.9);
e.preventDefault();
},false);
}
};
Here i am getting my element by using GetElementById to access my image tag is there any way to get access all the img tags in other tabs too.
I also tried getElementsbyClassName but its not working it just retrieving the nodeslist.
How can i access all three images here
Current BIN
you need to use different ID's
var img=document.getElementById("pic1");
var img=document.getElementById("pic2");`
You have assigned all three images the same id (id="pic"). You can't do that, ids must be unique.
If you change their ids, (ex: pic, pic2, pic3), and pass that in to your zoom function as an argument, then all the tabs will zoom.
So change the zoom function to look like this:
function zoom(zm, id) {
var img=document.getElementById(id);
...
}
And make your html look like this (just one for an example):
<div id="tabs-2">
<input type="button" value ="-" onClick="zoom(0.9, 'pic2')"/>
<input type="button" value ="+" onClick="zoom(1.1, 'pic2')"/>
<div id="thediv">
<img id="pic2" src="http://stereo-ssc.nascom.nasa.gov/beacon/t0193.jpg"/>
</div>
</div>
Now all three will zoom individually. Here's a jsbin showing it.
But, there's a bug. The variable you use to track the zoom state is being shared between the tabs. This means the "zoom limit" is not really enforced: you can just zoom one tab all the way down, then the next tab all the way up. Repeat this to make any of the images as big or as small as you want. I don't think this is what you want, but I'm going to leave it an exercise for you to fix.
So basically what I am looking for is how to have a random image javascript code but the images are in two different divs but I would like the random images to come from the same array.
I plan to take a JS class this summer so I don't have to ask anymore because I feel like this should be simple...
Currently I am just using the code from javascript kit in two different locations:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
but what I hope to achieve is:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="image1.gif"
myimages2[1]="image1a.gif"
myimages[2]="image2.gif"
myimages2[2]="image2a.gif"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0) ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
RENDERED CODE WITHIN DIVS
<div class="one"><img src="img1.gif"></div>
<div class="two"><img src="img1a.gif"></div>
REFRESHED
<div class="one"><img src="img2.gif"></div>
<div class="two"><img src="img2a.gif"></div>
Here's one particular approach.
I start out by identifying all of the variables I plan on using:
var rIndex1, rIndex2,
oContainer1, oContainer2,
aImages;
Now I assign initial references to DOM containers, as well as populate my images array:
oContainer1 = document.getElementById("left");
oContainer2 = document.getElementById("right");
aImages = ['http://placekitten.com/200/200','http://placekitten.com/201/201',
'http://placekitten.com/202/202','http://placekitten.com/203/203',
'http://placekitten.com/204/204','http://placekitten.com/205/205'];
Because I'll be generating random index values a few times, I create a simple function for this logic:
function rIndex ( iMax ) {
return Math.floor( Math.random() * iMax );
}
In order to see the effect over and over, I'm running the logic within an anonymous function, stored within an interval that runs every second. You, of course, could just wrap it up in a named function to be called once.
setInterval(function(){
Setting initial random values for my index variables.
rIndex1 = rIndex( aImages.length );
rIndex2 = rIndex( aImages.length );
We don't want both images to be the same, so as long as we have selected identical values, let's choose another index value for the second index.
while ( rIndex2 == rIndex1 ) rIndex2 = rIndex( aImages.length );
Lastly, I overwrite the innerHTML property of the containers with new image elements.
oContainer1.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex1 ] );
oContainer2.innerHTML = '<img src="%s" />'.replace( /%s/, aImages[ rIndex2 ] );
}, 1000);
Demo: http://jsbin.com/ubuxoj/edit#javascript,html
This could be improved upon a bit. For instance, it's possible that while aImages[2] is currently being shown in oContainer2, it may be reapplied the next time around. You could check to make sure you only select an image other than that which is currently being displayed in your container.
For what you are wanting to do, I don't see the point to store them on arrays and do complex stuff to get them.
If the URL paths are the same, there is no need to chose them from an array:
function refreshImages() {
var max = 10;
var rand = (Math.floor(Math.random() * max) + 1); //1-10
var src1 = "http://example.com/image" + rand + ".gif";
var src2 = "http://example.com/image" + rand + "a.gif";
document.getElementById("div1").innerHTML = "<img src='" + src1 + "' />";
document.getElementById("div2").innerHTML = "<img src='" + src2 + "' />";
}
window.onload = function() {//need to wait until the divs are loaded
refreshImages();
}
and in your HTML:
<div id="div1"></div>
<div id="div2"></div>
Note: I added +1 to rand because in your example you started at image1, if you want the possibility to start at image0, just remove the +1 and the range of possibilities will change to 0-9
jsFiddle demo (because the images don't exist, you need to see the source code)
If your purpose is to be extensible (e.g., if you don't know how many images you will have), I would normally recommend appending to the DOM and creating the <div/> randomly as well, and also looping to create the divs so you don't need to create them manually. However, if this is not the case, by using the pattern you have used, you could do something like this:
<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0>'
);
}
var myimages = [
"image1.gif", "image2.gif"
],
myimagesA = [
"image1a.gif", "image2a.gif"
];
</script>
<div class="one"><script>random_imglink(myimages);</script></div>
<div class="two"><script>random_imglink(myimagesA);</script></div>
We first make a random number which we reuse throughout the life of the script on this page load. Then we define the writing function and then make our 2 arrays available so they can be referenced by the function calls within the divs. It's hard to know exactly what you want without more detail, but hopefully this will give some ideas.