I need some help here. Whit this page i want to create own link tags with a image. When you click your image, you'll go to that page you have choose. I think i'm almost done but it does not work! What have i done wrong?!
When I click the img element to open the new page, the image pops up..
<head>
<meta charset="utf-8">
<title>Min Startsida</title>
<script type="text/javascript">
function newLink() {
var myNewLink = document.getElementById("link");
localStorage.setItem(link, myNewLink.value)
};
function newIcon() {
var myNewIcon = document.getElementById("icon");
localStorage.setItem(icon, myNewIcon.value)
};
function varIcon() {
document.getElementById("image").src = localStorage.getItem(icon)
};
</script>
</head>
<body>
<form>
<h1>lägg till länk</h1><br />
<input type="text" id="link"><br />
<input type="text" id="icon"><br />
<button onClick="newLink(), newIcon()">lägg till länk</button>
</form>
<section>
<img src="#" id="image" onLoad="varIcon()">
</section>
</body>
This must be a string:
localStorage.setItem("link", myNewLink.value)
^^^^
what happens here is that the element is used as a key as link is used as an id - key has to be a string. This goes for both the setItem methods and the getItem as well that you use later:
<a href="#" onClick="location.href = localStorage.getItem('link')">
Alos, this must be separated with a semi-column:
<button onClick="newLink(); newIcon()">
^
(I didn't look further than these points)
Related
This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 1 year ago.
For some reasons, I can't display #coupon with javascript, when i try to get elementById it displays the error message elementById undefined,
HTML
<html>
<head>
<title>Exercise</title>
<link rel="stylesheet" href="stylesheet.css">
<script src="javascript.js"></script>
</head>
<body>
<div class="inputi">
<p class="input-text">Une Jam?</p> <input placeholder="Sheno emrin..." type="text" id="inputId">
//checks input value
<button type="button" onclick="getInputValue()">Vazhdo</button>
// shows error message if it doesn't match the array
<p id="message"></p>
</div>
// i want to display this with javascript, after the login
<h1 id="coupon">You won giftcard </strong></h1>
<button id="coupon">abas</button>
</body>
</html>
JS ( the problem )
**
the problem getElementById is undefined, I want to display:block after the successful login attempt.
**
var zzz = getElementById("coupon")
if(zzz === "none") {
display:block; }
// document.writeln("<h1>Keni fituar kupon 50% ne <strong> Green & Protein </strong> </h1>");
// document.writeln('<input class="giftcode" placeholder="' +finalcode+'" type="text" id="inputId">');
display_image(images[z], 400, 400, 'Javascript');
document.write('<br>' + user[i]);
}
}
}
Two things:
getElementById should be document.getElementById
you need to move your script tag to the bottom of the body tag to ensure that the element is in the DOM when you select it
Use:
<html>
<head>
<title>Exercise</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<div class="inputi">
<p class="input-text">Une Jam?</p>
<input placeholder="Sheno emrin..." type="text" id="inputId">
//checks input value
<button type="button" onclick="getInputValue()">Vazhdo</button>
// shows error message if it doesn't match the array
<p id="message"></p>
</div>
// i want to display this with javascript, after the login
<h1 id="coupon">You won giftcard </h1>
<button id="coupon">abas</button>
<script src="javascript.js"></script>
</body>
</html>
From your code above it shows that you're trying to call a method getElementById() which you have not yet defined.
2ndly, you can only assign only 1 id in a document else it will not work.
you can do something like this
// i want to display this with javascript, after the login
<span id="coupon" style="display: none">
<h1>You won giftcard </strong></h1>
<button>abas</button>
</span>
what you meant to call is document.getElementById("coupon"); which is the right function to do.
so try this;
var zzz = document.getElementById("coupon");
i don't really know what your criteria is for a successful login but this show help
let say you set a variable as var success = "yes" on successful login
if(success === "yes"){
zzz.style.display = "block";
}
Call document.getElementById instead. Docs - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Try: document.getElementById
Instead of : getElementById
Because getElementById is a document method
First time ever touching javascript here, so bear with me.
My file structure looks like so:
I want to change the image in my HTML using js. Here's the relevant HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3A</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style/assignment_3.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="data/data.js"></script>
<script src="script/htmlMaker.js"></script>
<script src="script/assignment_3.js"></script>
<script id="news-detail-template" type="text/html">
<img class='news_photo' src='{{photo}}' >
<div class='news_heading'>{{heading}}</div>
<div class='date'>{{Date}}</div>
<div class='news_detail'>{{details}}</div>
</script>
<script id="news-item-template" type="text/html">
<div news_id='{{id}}' class='news_item' > {{heading}} </div>
<img class='news_img' src='data/NBA.jpg'>
</script>
</head>
<body>
<div class="newsDiv">
<div class="left">Latest</div>
<div id="news" class="marquee"></div>
<img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
</div>
<div id="detail" class="detail">
</div>
</body>
</html>
And then the corresponding js code in assignment_3.js:
function toggle(image) {
if (image.src != "data/pause.png")
{
image.src='data/pause.png';
}
else if (image.src == "data/pause.png")
{
image.src='data/play.png';
}
}
Obviously, something is amiss here, as the browser doesn't seem to recognize my image paths at all. How would I go about doing this correctly?
When you use image.src, it returns the full path of the image. In the if condition, you only checks the relative path of the image. To check for the relative path of the image, you can use image.getAttribute('src').
function toggle(image) {
if (image.getAttribute('src') == "data/pause.png") {
image.setAttribute('src', 'data/play.png');
} else {
image.setAttribute('src', 'data/pause.png');
}
}
<body>
<div class="newsDiv">
<div class="left">Latest</div>
<div id="news" class="marquee"></div>
<img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
</div>
<div id="detail" class="detail">
</div>
</body>
I have modelled a minimal, complete and verifiable example of your problem in this JSFiddle. I don't see any issues in your toggle logic. The only thing you need to consider is using img.getAttribute('src') instead of img.src. This is because
img.getAttribute('src') - Gives you the actual value that the HTML markup has set
img.src - Effective absolute path of the source
function toggle(img) {
// var playSrc = "data/play.png"; // to use your file instead
var playSrc = "https://cdn.iconscout.com/icon/premium/png-256-thumb/play-button-1516951-1285078.png";
// var pauseSrc = "data/pause.png"; // to use your file instead
var pauseSrc = "http://www.pngall.com/wp-content/uploads/5/Pause-Button-Transparent.png";
if (img.getAttribute('src') != pauseSrc)
{
img.setAttribute('src', pauseSrc);
}
else // The part if (image.src == "data/pause.png") is redundant
{
img.setAttribute('src', playSrc);
}
}
With that out of the way, you have a lot of junk in the <head> tag, which you need to remove (I have put them below). Probably, the code isn't working because of that.
<script id="news-detail-template" type="text/html">
<img class='news_photo' src='{{photo}}' >
<div class='news_heading'>{{heading}}</div>
<div class='date'>{{Date}}</div>
<div class='news_detail'>{{details}}</div>
</script>
<script id="news-item-template" type="text/html">
<div news_id='{{id}}' class='news_item' > {{heading}} </div>
<img class='news_img' src='data/NBA.jpg'>
</script>
As Harshana points out, you need to use the getAttribute function to check equality. You can set the image source using a regular assignment operator, but you cant use == to check for equality.
I want to set data-id after the user put a URL in an input, already tried a lot of samples that I found here and none of these worked...
//https://imgur.com/SPrSZV7 im trying with this url
function getUrl() {
var txt = document.getElementById('txtURL').value;
var novaURL = txt.replace('https://imgur.com/', '');
document.getElementById('resultado').innerHTML = novaURL;
imagem = document.getElementById('imagem').setAttribute('data-id', novaURL);
}
<script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>
<!-- ... -->
<input type="text" id="txtURL">
<input onclick="getUrl()" type="submit">
<h3 id="resultado">Resultado:</h3>
<blockquote id="imagem" class="imgur-embed-pub" lang="en" data-id="">
</blockquote>
the data-id should be SPrSZV7, I got in the console the error Cannot read property 'setAttribute' of null, why is this null?
What's happening is the imgur embed library is loading and overwriting your blockquote with an iframe, so your ID of "imagem" disappears when the iframe loads in its place. Trying wrapping the blockquote with a div container that has data-id attribute, and setting the data value there for reference. Or you can try and reference the imgur iframe ID that appears when embed happens: 'imgur-embed-iframe-pub-' instead of using a div wrapper. Please see the following example:
//https://imgur.com/SPrSZV7 im trying with this url
function getUrl() {
var txt = document.getElementById('txtURL').value;
var novaURL = txt.replace('https://imgur.com/', '');
document.getElementById('resultado').innerHTML = novaURL;
var imagem = document.getElementById('container-for-imgur');
imagem.dataset.id = novaURL;
console.log(imagem.dataset.id);
}
<script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>
<input type="text" id="txtURL" value="https://imgur.com/SPrSZV7" />
<input onclick="getUrl()" type="submit" />
<h3 id="resultado">Resultado:</h3>
<div id="container-for-imgur" data-id="">
<blockquote id="imagem" class="imgur-embed-pub" lang="en" data-id="">
</blockquote>
</div>
why is this null?
because you pass your JS code before body code ?
use dataset => https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
document.getElementById('imagem').dataset.id = novaURL;
remark : there is no return value so do not use imagem =
Your code works. You can see in inspect that the data attribute is correctly set up. You must have been experiencing a script load problem in which the content DOM is not loaded before the script execution.
//https://imgur.com/SPrSZV7 im trying with this url
function getUrl() {
var txt = document.getElementById('txtURL').value;
var novaURL = txt.replace('https://imgur.com/', '');
document.getElementById('resultado').innerHTML = novaURL;
imagem = document.getElementById('imagem').setAttribute('data-id', novaURL);
}
<input type="text" id="txtURL">
<input onclick="getUrl()" type="submit">
<h3 id="resultado">Resultado:</h3>
<blockquote id="imagem" class="imgur-embed-pub" lang="en" data-id="">
</blockquote>
I want to know if it's possible to have the text of an "a href" element to be the value of a textbox on a button click.
$("#btn").click(function(){
$("#myLink").text($("#Coordinate1").val());
$("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<button id="btn">Click</button>
<a id="myLink" href="#"><!-- THIS MUST BE VALUE OF "Coordinate1" --></a>
I hope the explanation is clear enought.
Thank you.
SOLVED: Added the code on the chosen answer below. Thanks everyone for your help all the solutions given by members worked how I wanted.
You can use following code:
function setLink() {
var t = document.getElementById("Coordinate1").value;
var h = "https://www.google.com/maps/place/" + t;
var link = document.getElementById("myLink");
link.href = h; //set link url
link.innerText = h; //set link text (remove this line if you don't want it)
}
<input type="text" id="Coordinate1" oninput="setLink()">
<input type="button" value="get link" onclick="setLink()">
<div>
<a id="myLink" href="#"></a><!-- THIS MUST BE VALUE OF "Coordinate1" -->
</div>
Seem you want to do something like this.
$("#btn").click(function(){
$("#myLink").text($("#Coordinate1").val());
$("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
<input type="text" id="Coordinate1">
<a id="myLink" href="#"><!-- THIS MUST BE VALUE OF "Coordinate1" --></a>
Yes, you can, but you have to do it when the user click something or finishes typing the link, or some other event. Here I use a button:
$("#change").click(function() { // when the button is clicked, change the href to whatever in the input + the root, and change it's text to the value as well
var value = $("#Coordinate1").val();
$("#myLink").prop("href", "https://www.google.com/maps/place/" + value) // change the href
.text(value); // change the text content
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<a id="myLink" href="#">
<!-- THIS MUST BE VALUE OF "Coordinate1" -->
</a>
<button id="change">Change</button>
I believe that this is what you were asking for. I took the code you already had and just placed it within the click of a button element I added to the page. Also be sure to give an actual text value inside the a tag or it won't be clickable to the user.
$("#update").click(function() {
$("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<button id="update">update</button>
<a id="myLink" href="#">
Link
<!-- THIS MUST BE VALUE OF "Coordinate1" -->
</a>
I'm still quite new to JavaScript so sorry for any incorrect terms etc.
I've got an image changer that uses buttons, and has the image stored within the button, but I know there's a way to compress these into an array and print out image by using 'image_array(0)' for example to get the image from the array.
Code below;
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button onclick="document.getElementById('image').src='green_light.jpg'">Green</button>
<p></p>
<button onclick="document.getElementById('image').src='yellow_light.jpg'">Amber</button>
<p></p>
<button onclick="document.getElementById('image').src='red_and_yellow_light.jpg'">Red/Amber</button>
<p></p>
<button onclick="document.getElementById('image').src='red_light.jpg'">Red</button>
<p></p>
<button onclick="document.getElementById('image').src='blank_light.jpg'">Reset</button>
</body>
</html>
I looked for a good 20 minutes for a similar thread but couldn't find anything specific, and with a cheap understanding of JavaScript and HTML, everything I found was too vague for what I'm looking for.
Thanks in advance.
The image is not stored within the button, you are just changing the image source on click. If by compress you mean that the image will have less bytes, then you are wrong, an array does not do that. It just keeps information contiguously. The only advantage is you can handle more dynamic things and maybe be more organized.
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_ligh", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Green</button>
<p></p>
<button class = "change-image">Amber</button>
<p></p>
<button class = "change-image">Red/Amber</button>
<p></p>
<button class = "change-image">Red</button>
<p></p>
<button class = "change-image">Reset</button>
</body>
</html>
If I understand you correctly, you need altering the source of images through keeping images in an array.
[].slice.call(document.querySelectorAll('button'), 0)
Above line is to access all buttons in the DOM.
Do something like this.
var images = ['green_light.jpg',
'yellow_light.jpg',
'red_and_yellow_light.jpg',
'red_light.jpg',
'blank_light.jpg'
];
var imageElement = document.getElementById('image');
[].slice.call(document.querySelectorAll('button'), 0).forEach(function(button, index){
button.addEventListener('click',function(e){
imageElement.src = images[index];
console.log("Image changed to: ", images[index]);
});
});
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button>Green</button>
<p></p>
<button>Amber</button>
<p></p>
<button>Red/Amber</button>
<p></p>
<button>Red</button>
<p></p>
<button>Reset</button>
</body>
</html>