I am very new to Javascript, I am making a HTML website.
Since I am new to Javascript, I do not know how to show an image, and when the image is clicked make it link to a page.
I know how to do it in HTML, but due to my free host if I wasn't to make a single change to how many images there are (which I will do a lot), or where it links to (which will be shown on every page) I will need to go through every page.
All I need it to do is open the page on the same tab.
Try this:
var img = new Image();
img.src = 'image.png';
img.onclick = function() {
window.location.href = 'http://putyourlocationhere/';
};
document.body.appendChild(img);
Without more information, I'm going to offer this as a relatively cross-browser approach, which will append an img element wrapped in an a element. This works with the following (simple) HTML:
<form action="#" method="post">
<label for="imgURL">image URL:</label>
<input type="url" id="imgURL" />
<label for="pageURL">page URL:</label>
<input type="url" id="pageURL" />
<button id="imgAdd">add image</button>
</form>
And the following JavaScript:
// a simple check to *try* and ensure valid URIs are used:
function protocolCheck(link) {
var proto = ['http:', 'https:'];
for (var i = 0, len = proto.length; i < len; i++) {
// if the link begins with a valid protocol, return the link
if (link.indexOf(proto[i]) === 0) {
return link;
}
}
// otherwise assume it doesn't, prepend a valid protocol, and return that:
return document.location.protocol + '//' + link;
}
function createImage(e) {
// stop the default event from happening:
e.preventDefault();
var parent = this.parentNode;
/* checking the protocol (calling the previous function),
of the URIs provided in the text input elements: */
src = protocolCheck(document.getElementById('imgURL').value);
href = protocolCheck(document.getElementById('pageURL').value);
// creating an 'img' element, and an 'a' element
var img = document.createElement('img'),
a = document.createElement('a');
// setting the src attribute to the (hopefully) valid URI from above
img.src = src;
// setting the href attribute to the (hopefully) valid URI from above
a.href = href;
// appending the 'img' to the 'a'
a.appendChild(img);
// inserting the 'a' element *after* the 'form' element
parent.parentNode.insertBefore(a, parent.nextSibling);
}
var addButton = document.getElementById('imgAdd');
addButton.onclick = createImage;
JS Fiddle demo.
Related
I want to set img src=" " with a function in javascript that changes the picture upon a variable and checks values:
javascript file code:
function myFunctionstatus(){
var ledactual=document.getElementById("ledonof").value
var image = document.getElementById('ledPic');
if (ledactual==ledon) {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-c
content/uploads/OFFbulb.jpg";
}
if (ledactual==ledoff){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-
content/uploads/ONbulb.jpg";
}
} };
img src in html file:
<img id="ledPic" [src]="myFunctionstatus()" >
but it didn't work with me and the picture didn't appear! the script is working, I tested with a button:
<input type="button" id="ledonof" onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">
how can I set img src with a function?
I can't comment on the php that you're using to get the status, but the below is a working javascript example:
function myFunctionstatus(){
var input = document.getElementById("ledonof");
var image = document.getElementById('ledPic');
if (input.value == "on") {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
input.value = "off"
} else if (input.value == "off"){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
input.value = "on"
}
}
myFunctionstatus()
<img id="ledPic" />
<input type="button" id="ledonof" onclick="myFunctionstatus();" class="ledonoff" value="on">
As noted by others, src doesn't support function calls (and you don't even return anything from your function call), so you need to run the function once at the start to set the image to the initial status.
You need to set an initial state manually
function switchStatus() {
let switchButton = document.getElementById('ledonof');
let img = document.getElementById('ledPic');
if(switchButton.value == "ledon") {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
switchButton.value = "ledoff";
} else {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
switchButton.value = "ledon";
}
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof" onclick="switchStatus();" value="ledoff">
img src attr does not support function call. Whatever you pass in the src will be considered as url(relative or otherwise).
Please refer https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes
So what you need to do is call the function before/loading your element and change the src then. The simplest form would be following
`<script>
(function() {
// your page initialization code here
// the DOM will be available here
// call the function here
})();
</script>`
You can't do this. The src attribute of an image element can't be interpreted as javascript when the HTML is interpreted.
initially, you need to set src, and on button click, you can toggle image by changing image src.
*update here is my code edit as you see working) https://codeshare.io/a3ZJ9g
i need to pass on a javascript varible to a html link...
my original question was here HTML5 video get currentTime not working with media events javscript addEventListener
working code:
<script>
var media = document.getElementById('myVideo');
// durationchange
var isdurationchange = function(e) {
$("#output").html(media.currentTime);
var x = document.createElement("a");
};
media.addEventListener("timeupdate", isdurationchange, true)
</script>
that code works
but i need it to echo the currentTime value to the html page such as
document.write("<a href=/time.htm?currentTime='.media.addEventListener("timeupdate", isdurationchange, true).'>link</a>;);
so it would print out
<a href=time.htm?currentTime=currenttimefromjavascript>link</a>
thank you
i did read:
how to pass javascript variable to html tag
How can I pass value from javascript to html?
someone suggested:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
but where does that go?
document.write tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
If, for an element you create dynamically, you want to change its href on every timeupdate, you would do:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
I have tried so many examples but none of them works
t
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox">Type something here</textarea>
<button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
here is a code which is working good but i need to download automatically without using link
is it possible?
You could use the following script to create and save automatically a file from the browser to your operating system. This code works only on latest version of Chrome.
What the script does?
It creates a temporary URL containing the specified File object or Blob object - Programmatically click the link just created so the file will be download by the browser.
Immediately after remove the link from the page.
var saveDataToFile = function (data, fileName, properties) {
window.URL = window.URL || window.webkitURL;
var file = new File(data, fileName, properties),
link = document.createElement('a');
link.href = window.URL.createObjectURL(file);
link.download = fileName;
document.body.appendChild(link);
link.click();
var timer = setTimeout(function () {
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
clearTimeout(timer);
}, 100);
};
If you deconstruct this problem, there's a few key points:
Initially, when the user hasn't typed text into the textarea, the button should not be visible. (I may be wrong here though)
When the user starts typing, the button has to appear.
Whatever is inside the textarea after that, has to be downloadable per click on the button.
So, it's a matter of two event listeners.
The first one is "focus": when the textarea received focus, its value is an empty string, and the button appears. The user hasn't yet started typing, but there's actually no need to force them to.
The second one is "change": per every change in the field, we need to update the value of href attribute of the link, so that when the user clicks that element, file download happens, and the content is precisely what's inside the textarea. Good thing, a function passed to "change" event listener is executed with the first argument instance of Event, which means you can do event.target.value to get the new value per every change. It means, the whole text from within textarea.
Summing up, it's
<textarea id="textbox" placeholder="Type something here"></textarea>
<a download="info.txt" id="create" href="#" style="display: none;">Create file</a>
and
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create');
var textbox = document.getElementById('textbox');
textbox.addEventListener('focus', function (event) {
create.style.display = 'block';
create.href = makeTextFile(''); // initially, the text is empty.
});
textbox.addEventListener('change', function (event) {
create.href = makeTextFile(event.target.value); // per every change, update value of href attribute of #create
});
})();
Take note that only a element can have href assigned with Blob value. Using a button element would be a little bit more complicated, so it might be easier to just make the a element look like a button.
See the Codepen to make sure it works as you expect, or feel free to edit it otherwise.
Hi I have markup sent to me from a server and I set it as the innerHTML of a div element for the purpose of traversing the tree, finding image nodes, and changing their src values. Is there a way to prevent the original src value from being downloaded?
Here is what I am doing
function replaceImageSrcsInMarkup(markup) {
var div = document.createElement('div');
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(replaceSrc);
return div.innerHTML;
}
The problem is that in browsers as soon as you do:
var img = document.createElement('img'); img.src = 'someurl.com' the browser fires off a request to someurl.com. Is there a way to prevent this without resorting to parsing the markup myself? If there is in no other way does anyone know a good way of parsing the markup with as little code as possible to accomplish my goal?
I know you are already happy with your solution, but I think it would be worth sharing a safe method for future users.
You can now simply use the DOMParser object to generate an external document from your HTML string, instead of using a div created by your current document as container.
DOMParser specifically avoids the pitfalls mentioned in the question and other threats: no img src download, no JavaScript execution, even in elements attributes.
So in your case you can safely do:
function replaceImageSrcsInMarkup(markup) {
var parser = new DOMParser(),
doc = parser.parseFromString(markup, "text/html");
// Manipulate `doc` as a regular document
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i += 1) {
replaceSrc(images[i]);
}
return doc.body.innerHTML;
}
Demo: http://jsfiddle.net/94b7gyg9/1/
Note: with your current code, browsers will still try downloading the resource initially specified in your img nodes src attribute, even if you change it before the end of JS execution. Trace network transactions in this demo: http://jsfiddle.net/94b7gyg9/
Rather than append the new markup to the DOM before you change the img sources, create an element, set it's inner HTML, change the source of the images and then finally, append the changed markup to the page.
Here's a fully-worked sample.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
//function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
//function newTxt(txt){return document.createTextNode(txt);}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClick, false);
}
var dummyString = "<img src='img/girl.png'/><img src='img/gfx07.jpg'/>";
function onGoBtnClick(evt)
{
var div = newEl('div');
div.innerHTML = dummyString;
var mImgs = allByTag('img', div);
for (var i=0, n=mImgs.length; i<n; i++)
{
mImgs[i].src = "img/murderface.jpg";
}
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>GO!</button>
</body>
</html>
You could directly parse the markup string using a regex to replace the img src. Searching for all the img src urls in the string and then replacing them with the new url.
var regex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var imgUrls = [];
while ( m = regex.exec( markup ) ) {
imgUrls.push( m[1] );
}
imgUrls.forEach(function(url) {
markup = markup.replace(url,'new-url');
});
Another solution might be, if you have access to it, to set the all the img src to an empty string, and put the url in in a data-src attribute. Having your markup string look like something like this
markup = '
';
Then setting this markup to your div.innerHTML won't trigger any download from the browser. And you can still parse it using regular DOM selector.
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(function(img){
var oldSrc = img.getAttribute('data-src');
img.setAttribute('src', 'new-url');
});
I have a page that has a set of <div> elements, and each one has an anchor tag associated with it. It looks something like this:
<a name="anchor-0"></a>
<div id="div0">Some stuff</div>
<a name="anchor-1"></a>
<div id="div1">More stuff</div>
<a name="anchor-2"></a>
<div id="div2">Yet more stuff</div>
The problem is that this set of <div> and <a> tags are generated by Javascript, and so they don't exist until after the page has been created. When I create a link like this:
http://www.mywebsite.com/mypage.html#anchor-2
... it loads the page but does not jump to the anchor-2 position, which is only created some time after the browser has had time to execute the Javascript that generated it.
How can I get the browser to move to the selected anchor tag position once the Javascript has generated them?
Here is essentially what the Javascript that is generating the HTML looks like:
function init() {
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
gapi.client.load('blogger', 'v2', function() {
var request = gapi.client.blogger.posts.list({
'blogId': 'xxxxxxxxxxxxxxxxxxxxxxxx',
'fields': 'items(content,title)'
});
request.execute(function(response) {
var main = document.getElementById("main");
var anchor = 0;
for (var i = 0; i < response.items.length; i++)
{
var Div = document.createElement("div")
$(Div).append(response.items[i].title);
$(main).append(Div);
anchor = document.createElement("a");
anchor.name = "anchor-" + anchor;
anchor = anchor +1;
}
});
});
}
after creation of element, you could do:
location.hash = "#anchor-2";
or using scrollIntoView
element = document.getElementById('your_element-id');
element.scrollIntoView();
get the hash value from url, by doing something like::
var hashVal = window.location.hash.substr(1);
//then jump to that hash
location.hash = "#" + hashVal;