In this program I created object and instances of it and stored those instances in array. I am retrieving array index by getting the modulo of minutes with the length of the array. I am trying to display link in div tag and I should be able to see different link every minute. Upon clicking link it should show different url. and set the timer to run every minute. For that I have created setInterval(). but it doesn't seem to work. Can anyone help me?
code:
<!DOCTYPE html>
<html>
<head>
<style>
.myDiv{
width: 750px;
height: 150px;
border: #CED8BC 3px solid;
border-radius: 20px;
position: absolute;
top: 30%;
left: 20%;
}
div p {
text-align: center;
font-family: monospace;
font-size: 30px;
}
a{
text-align: center;
text-decoration: none;
color: #3bb570;
}
a:hover{
color:#efa5db
}
</style>
<title>lab15</title>
</head>
<body background="lab15_images/pink.jpg">
<div class="myDiv" id="div">
<p> Click on the link to see a website. </p>
<!-- <p><b> </b></p> -->
<p id="link"> </p>
</div>
<script>
function site(the_url, website_name) {
this.the_url = the_url;
this.website_name = website_name;
}
var myWebsite = new site("http://www.cnn.com/", "CNN");
var myWebsite2 = new site("http://www.bbc.com/news", "BBC");
var myWebsite3 = new site("http://www.foxnews.com/", "FOX NEWS");
var myWebsite4 = new site("http://abcnews.go.com/", "ABC NEWS");
var myWebsite5 = new site("https://www.cbsnews.com/", "CBS NEWS");
var instances = new Array(myWebsite, myWebsite2, myWebsite3, myWebsite4, myWebsite5);
setInterval(changeLink, 60000);
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
var counter = 0;
var ele = document.getElementbyId("link");
ele.innerHTML = instances[counter];
counter++;
if(counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementbyId("div");
a.href = site.the_url;
a.innerHTML = site.website_name
myDiv.appendChild(a);
document.body.appendChild(myDiv);
}
</script>
</body>
</html>
Fixed your semicolons and getElementById typos. Here is the working code.
function site(the_url, website_name) {
this.the_url = the_url;
this.website_name = website_name;
}
var myWebsite = new site("http://www.cnn.com/", "CNN");
var myWebsite2 = new site("http://www.bbc.com/news", "BBC");
var myWebsite3 = new site("http://www.foxnews.com/", "FOX NEWS");
var myWebsite4 = new site("http://abcnews.go.com/", "ABC NEWS");
var myWebsite5 = new site("https://www.cbsnews.com/", "CBS NEWS");
var instances = new Array(myWebsite, myWebsite2, myWebsite3, myWebsite4, myWebsite5);
// call changeLink once to display on page load
changeLink();
// interval changed to 3 seconds so that you dont need to wait a minute for the result
setInterval(changeLink, 3000);
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length;
var site = instances[index];
var counter = 0;
var ele = document.getElementById("link");
counter++;
if (counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementById("div");
a.href = site.the_url;
a.innerHTML = site.website_name;
ele.innerHTML = '';
ele.appendChild(a);
}
.myDiv {
width: 750px;
height: 150px;
border: #CED8BC 3px solid;
border-radius: 20px;
position: absolute;
top: 30%;
left: 20%;
}
div p {
text-align: center;
font-family: monospace;
font-size: 30px;
}
a {
text-align: center;
text-decoration: none;
color: #3bb570;
}
a:hover {
color: #efa5db
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<title>lab15</title>
</head>
<body background="lab15_images/pink.jpg">
<div class="myDiv" id="div">
<p> Click on the link to see a website. </p>
<!-- <p><b> </b></p> -->
<p id="link"> </p>
</div>
</body>
</html>
Move var counter = 0; out of the function.
Also, as #guest271314 pointed, you have to capitialize the by in:
var ele = document.getElementById("link");
/* ... */
var myDiv = document.getElementbyId("div");
Final code:
var counter = 0;
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
//var counter = 0;
var ele = document.getElementById("link"); //Capitalize By
ele.innerHTML = instances[counter];
counter++;
if (counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementById("div"); //Capitalize By
a.href = site.the_url;
a.innerHTML = site.website_name
myDiv.appendChild(a);
document.body.appendChild(myDiv);
}
Related
I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)
I just started working with Javascript and I am trying to make my first "Todo App".
The problem is, that my delete button which should be related to specific div is deleting only last div.
To better understaing check out my code on Codepen:
https://codepen.io/anon/pen/QVPxmG
or here:
var books = ["Bang-1","Bang-2","Bang-3","Bang-4"];
var wrapper = document.querySelector(".wrapper");
var element_div = document.querySelector(".element_div");
var load_button = document.querySelector(".load");
load_button.addEventListener("click", function(){
for(var x=0;x<books.length;x++){
var div = document.createElement("div");
div.setAttribute("class","element_div " + "element_div"+x);
wrapper.appendChild(div);
var element = document.createElement("p");
div.appendChild(element);
element.setAttribute("class", "element"+x);
element.innerHTML = books[x];
var del = document.createElement("button");
del.setAttribute("class", "delete"+x);
div.appendChild(del);
del.innerHTML = 'Delete';
del.addEventListener("click", function(){
div.remove();
},false);
}
},false);
var clear = document.querySelector(".clear");
clear.addEventListener("click", function(){
wrapper.innerHTML = "";
},false);
What Should I change to delete proper div?
Thanks, Mike.
The problem in your case come because of closure,you have declared all your variables using var which will belong to the functional scope and hence when you click on delete, the div that is deleted is the last div since that is what div variable points to after the for loop iteration.
Changing everything to let will work, since let is block scoped and the declaration will be limited to within the for loop
for(let x=0;x<books.length;x++){
let div = document.createElement("div");
div.setAttribute("class","element_div " + "element_div"+x);
wrapper.appendChild(div);
let element = document.createElement("p");
div.appendChild(element);
element.setAttribute("class", "element"+x);
element.innerHTML = books[x];
let del = document.createElement("button");
del.setAttribute("class", "delete"+x);
div.appendChild(del);
del.innerHTML = 'Delete';
del.addEventListener("click", function(){
div.remove();
},false);
}
},false);
Working codepen
You have to use "this" instead of "div" in click event. Something like this:
this.parentElement.remove();
div will have the content after for loop ends. You should capture the correct div for every iteration like below, using pure javascript's immediately invoking function
var books = ["Bang-1", "Bang-2", "Bang-3", "Bang-4"];
var wrapper = document.querySelector(".wrapper");
var load_button = document.querySelector(".load");
load_button.addEventListener("click", function() {
for (var x = 0; x < books.length; x++) {
var div = document.createElement("div");
(function(div) { // Immediately invoking function - IIFE
div.setAttribute("class", "element_div " + "element_div" + x);
wrapper.appendChild(div);
var element = document.createElement("p");
div.appendChild(element);
element.setAttribute("class", "element" + x);
element.innerHTML = books[x];
var del = document.createElement("button");
del.setAttribute("class", "delete" + x);
div.appendChild(del);
del.innerHTML = 'Delete';
del.addEventListener("click", function() {
div.remove();
}, false);
})(div);
}
}, false);
var clear = document.querySelector(".clear");
clear.addEventListener("click", function() {
wrapper.innerHTML = "";
}, false);
* {
margin: 0;
padding: 0;
}
.container {
width: 300px;
height: 250px;
position: relative;
}
.container .wrapper {
width: 300px;
height: 200px;
padding: 10px;
background: aqua;
position: relative;
}
.container .wrapper .element_div {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.container .load {
position: absolute;
bottom: 0px;
}
.container .clear {
position: absolute;
bottom: 0px;
right: 10px;
}
<div class="container">
<div class="wrapper" id="wrapper">
<div class="element_div">
<p class="element">Bang</p>
<button class="delete">Delete</button>
</div>
</div>
<button class="load">LOAD</button>
<button class="clear">CLLEAR</button>
</div>
I have made 24 buttons with a for loop, and want button from number 1 to 24 to give a message like this.
"you clicked on button 1"
"you clicked on button 2" and so on.
I have been able to split the 3 first buttons so they say "button 1" "2" "3", but that is done by 3 if statements, which means i would need 23-24 ish if statements to get them all to do as I want. That's not a very efficient way to do it.
Is there a good way to get the button id to add +1 after "knapp" every time the loop runs ? something like this element.id = "knapp" + 1; < so the id become knapp1, knapp2, knapp3 as the loop keep running 24 times ?
html:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<script src="Assignment06.js"></script>
<style>
h1 {
text-align: center;
}
div {
background-color: forestgreen;
border: solid 1px #000;
display: inline-block;
width: 100px;
height: 100px;
padding: 10px
}
#panel {
width: 610px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Assignment06</h1>
<p id = "panel"></p>
</body>
</html>
Javascript:
function dag(){
knapp = window.alert("Du trykket knapp 1");
}
function dag2(){
window.alert("Du trykket knapp 2");
}
function dag3(){
window.alert("Du trykket knapp 3");
}
function init(){
knapper();
}
function knapper(){
for (var antall = 1; antall <= 24; antall++){
if(antall == 1){
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp";
knapp = element.addEventListener("click", dag);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
else if (antall == 2){
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp2";
knapp2 = element.addEventListener("click", dag2);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
else{
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp3";
knapp3 = element.addEventListener("click", dag3);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
}
}
window.onload = init;
You can save the id in the dataset of the <div /> element.
function knapper() {
var panel = document.getElementById("panel");
for (var antall = 1; antall <= 10; antall++) {
var element = document.createElement("div");
element.innerHTML = antall;
element.dataset.id = antall;
element.addEventListener("click", dag);
panel.appendChild(element);
}
}
function dag(evt) {
alert(evt.target.dataset.id);
}
window.onload = knapper;
#panel div {
width: 50px;
height: 50px;
border: solid 1px black;
float: left;
}
<div id="panel"></div>
To directly answer your question without suggestions:
You already have a counter in the for loop (antall). You can just use that variable and concatenate it on the end of the string that you're using as an id.
element.id = "knapp" + antall;
There is a simple game. The left and right sides are identical, except for one thing: the left side has one extra face. The user needs to find out and click on that extra face (lastChild). It will trigger the function to double the face quantity.
The problem is - all the faces in my game are lastChild. Where is the problem?
Thanks!
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<title>Matching Game. Part 3.</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
<script>
function generateFaces(){
var numberOfFaces = 5;
//var theLeftSide = document.getElementById("leftSide");
for(var i=0; i < numberOfFaces; i++) {
var smileImage = document.createElement("img");
smileImage.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topPosition = Math.floor(Math.random()* 400) + 1;
var leftPosition = Math.floor(Math.random()* 400) + 1;
smileImage.style.top = topPosition + "px";
smileImage.style.left = leftPosition + "px";
leftSide.appendChild(smileImage);
var leftSideImages = leftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
rightSide.appendChild(leftSideImages);
leftSide.lastChild.style.background = "red";
var theBody = document.getElementsByTagName("body")[0];
leftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
}
}
}
</script>
</head>
<body onload = "generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
You are binding your click event to every element in the loop. You first need to over-ride the previous handler and then re-bind it to the last element.
function generateFaces(){
var numberOfFaces = 5;
var leftSide = document.getElementById("leftSide");
var rightSide = document.getElementById("rightSide");
for(var i=0; i < numberOfFaces; i++) {
var smileImage = document.createElement("img");
smileImage.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topPosition = Math.floor(Math.random()* 400) + 1;
var leftPosition = Math.floor(Math.random()* 400) + 1;
smileImage.style.top = topPosition + "px";
smileImage.style.left = leftPosition + "px";
leftSide.appendChild(smileImage);
var leftSideImages = leftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
rightSide.appendChild(leftSideImages);
leftSide.lastChild.style.background = "red";
var theBody = document.getElementsByTagName("body")[0];
}
var pics = document.getElementsByTagName("img");
for(i=0;i<pics.length;i++){
pics[i].onclick = function() {
return false;
}
}
leftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
<body onload = "generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
Alright, so I have been killing myself over this for a while now. I simply want to take an XML response containing names from my arduino and then dynamically create buttons. Each button needs to say the name and have the name as its id for the GetDrink function to use to send back to the arduino. If anyone can give me some help, maybe some code to work off of it would be appreciated.
I am able to have a button call the CreateButton function to create more buttons which all work. But I need to dynamically create the buttons off of the XML response. Also, this has to be done strictly using JavaScript and HTML.
<!DOCTYPE html>
<html>
<head>
<title>The AutoBar</title>
<script>
// Drinks
strDRINK1 = "";
function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
var count;
var num_an = this.responseXML.getElementsByTagName('alcohol').length;
for (count = 0; count < num_an; count++) {
document.getElementsByClassName("AlcStatus")[count].innerHTML =
this.responseXML.getElementsByTagName('alcohol')[count].childNodes[0].nodeValue;
}
}
}
}
}
request.open("GET", "ajax_inputs" + strDRINK1 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);**strong text**
strDRINK1 = "";
}
function GetDrink(clicked_id)
{
strDRINK1 = "&" + clicked_id;
document.getElementById("AlcStatus").innerHTML = "Your " + clicked_id + " is being made";
}
function CreateButton(Drink_Name)
{
myButton = document.createElement("input");
myButton.type = "button";
myButton.value = Drink_Name;
placeHolder = document.getElementById("button");
placeHolder.appendChild(myButton);
myButton.id = Drink_Name;
myButton.onclick = function()
{
strDRINK1 = "&" + myButton.id;
document.getElementById("AlcStatus").innerHTML = "Your " + myButton.id + " is being made";
}
}
</script>
<style>
.IO_box {
float: left;
margin: 0 20px 20px 0;
border: 1px solid blue;
padding: 0 5px 0 5px;
width: 320px;
}
h1 {
font-size: 320%;
color: blue;
margin: 0 0 10px 0;
}
h2 {
font-size: 200%;
color: #5734E6;
margin: 5px 0 5px 0;
}
p, form, button {
font-size: 180%;
color: #252525;
}
.small_text {
font-size: 70%;
color: #737373;
}
</style>
</head>
<body onload="GetArduinoIO()" BGCOLOR="#F5F6CE">
<p> <center><img src="pic.jpg" /></center><p>
<div class="IO_box">
<div id="button"></div>
</div>
<div class="IO_box">
<h2><span class="AlcStatus">...</span></h2>
</div>
<div>
<button onclick="location.href='Edit_Bar.htm'">Edit Bar Menu</button>
<div>
</body>
</html>
Something like this?
var xml = "<items><alcohol>Bourbon</alcohol><alcohol>Gin</alcohol><alcohol>Whiskey</alcohol></items>";
var parser = new DOMParser();
var dom = parser.parseFromString(xml, "text/xml");
var alcohol = dom.querySelectorAll('alcohol');
function getDrink(event) {
alert(event.target.value);
}
function makeButton(value) {
var b = document.createElement('button');
b.innerHTML = value;
b.value = value;
b.id = value;
b.addEventListener('click', getDrink);
return b;
}
var list = document.getElementById('buttons');
for(var i = 0; i < alcohol.length; i++ ) {
var b = makeButton(alcohol[i].firstChild.nodeValue);
var li = document.createElement('li');
li.appendChild(b);
list.appendChild(li);
}
<ul id="buttons"></ul>