How do I replace an HTML button with several images using javascript? - javascript

I currently have:
//javascript
function morshots()
{
var mordor = document.getElementById("ss1");
var shots= (
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
}
and
<!--html-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="screenshots.js"></script>
</head>
<body>
<div id="ss1">
<button onClick="morshots();">View Screenshots</button>
</div>
</body>
</html>
Currently the button does nothing on click. What I want is for the images to replace the button on the page. This is not my entire code, however I omitted the non-pertinent piece of code for readability.
--EDIT--
I have added escapes for the inner quotes and non-escaped quotes around the image tags. I am still getting the same result with the page (button click does nothing)
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}'
---EDIT2:----
Fixed it, the working code reads:
function morshots()
{var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}

Add the <img>s within quotes:
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">';
}

Did you check your JavaScript console for errors?
// syntax error:
var shots= (
// syntax error:
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
You need to pass a string to mordor.innerHTML - wrap your html in quotes. I'm not sure what you're trying to do with shots.

Add quotes and escape them withing html adding backslash \ before them:
var mordor = document.getElementById("ss1");
mordor.onclick = function () {
var shots= "<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">";
mordor.innerHTML = shots;
};

Related

Change the inner HTML with another HTML code block of a div and a script

I have been struggling with this so hopefully someone can help!
So I am looking to change the inner html of a paragraph to another html element containing a div and script when my frame receives a message from the page code. I have this working only for when the inner html is set to replace with a normal string
like this
document.getElementById('demo').innerHTML = "testing" ;
the correct replacement shows up here
<p id="demo">testing</p>
but when I try and pass in the other html to replace that section like this:
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>';
it does not work. I don't think it is a quotation issue because I wrapped the outsides of it with single quotes. not sure what else to try. Below is the full html and I would appreciate any help!
<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>'
;
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">
should put html here
</p>
</body>
</html>
The major issue is the </script> closing tag in your code. It closes YOUR block, not the block you are inserting.
You have to do so:
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></scr"+"ipt>";
Second, script you insert with innerHTML wont run. Use document.createElement('script') instead
UPDATE
Here is the jsFiddle: https://jsfiddle.net/ArtyomShegeda/62fdybc0/21/
You may consider swapping the Quotes used:
function insertMessage(msg) {
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></script>";
document.getElementById('demo').innerHTML = myHtml;
}
This may add it, yet may not render it. You might consider creating the elements and appending them.
function insertMessage(msg) {
var tlkio = document.createElement("div");
tlkio.style.width = "100%";
tlkio.style.width = "400px";
tlkio.setAttribute('data-channel', 'regerhtrh');
tlkio.setAttribute('data-theme', 'theme--night');
var tlkScript = document.createElement("script");
tlkScript.src = 'https://tlk.io/embed.js';
tlkScript.type = 'text/javascript';
tlkScript.async = true;
document.getElementById('demo').append(tlkio, tlkScript);
}
Based on some research here: load scripts asynchronously, it may be best to append the script to the <head>.
Hope that helps.
Update 1
Per your fiddle, once updated, it is working as you suggested: https://jsfiddle.net/Twisty/62fdybc0/7/
The following is added to #myDIV element:
<div style="width: 100%; height: 400px;" data-channel="regerhtrh" data-theme="theme--night"></div><script src="https://tlk.io/embed.js" type="text/javascript" async="async"></script>

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

what is wrong with my html code?

I am new to html. I have been debugging my code for the past 5 hours and I cannot figure out what is wrong with it. I reference a package that only has 1 method, which is get_country. The link to the packages I use are here. https://github.com/nickewing/line-reader and https://github.com/totemstech/country-reverse-geocoding
<html>
<head>
<script type="text/javascript">
function a() {
var lineReader = require('line-reader');
lineReader.eachLine(‘Location.txt', function(line, last) {
var b= line.split(“,”,2)
var lat= parseInt(b[0])
var lng= parseInt(b[1])
var crg = require('country-reverse-geocoding').country_reverse_geocoding();
var country = crg.get_country(lat, lng);
console.log(country.name); //
if (/* done */) {
return false; // stop reading
}
});
}
</script>
</head>
<body>
<button type="button" onclick=“a()>Click run reverse geocoder</button>
</body>
</html>
You're missing a closing quote, you have:
<button type="button" onclick=“a()>Click run reverse geocoder</button>
and it should be:
<button type="button" onclick="a()">Click run reverse geocoder</button>
Aside from the missing quote in the other answer, you have a few quotes that are not standard or double quotes. Here are the ones that a JS parser found:
lineReader.eachLine(‘Location.txt... - The single quote before Location is not a single quote
var b= line.split(“,” - These are not really double quotes - perhaps convert to single quotes or use actual double quotes
Additionally, after your closing brace to the function, you have some extra closing braces and parenthesis.
); - The parenthesis and semicolon
} - The last bracket
Hope this helps
in javascript or in jQuery try to use "" or '' not that curely “” quotes
and its input element in html having attribute type or use button element instead and remove type attribute. hope it would work now
<html>
<head>
<script type="text/javascript">
function a()
{
var lineReader = require('line-reader');
lineReader.eachLine('Location.txt', function(line, last) {
var b= line.split(',',2);
var lat= parseInt(b[0]);
var lng= parseInt(b[1]);
var crg = require('country-reverse-geocoding').country_reverse_geocoding();
var country = crg.get_country(lat, lng);
console.log(country.name); //
if (/* done */) {
return false; // stop reading
}
});
}
</script>
</head>
<body>
<input type="button" onclick='a()'>Click run reverse geocoder</button>
</body>
</html>
EDIT:
sorry IDK why the formating of code it not being applied here.
Syntax error:
onclick="a()" - Missing closing quotes.

TypeError: getElementById is null

<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

Categories

Resources