Preventing src from being changed - javascript

Is it possible to fix an image src set by a javascript function and returned to a HTML tag.
I have a set of array objects that includes, amongst other details, the location of an image for each object:
Person[1]= {
Image:"Adam.jpg",
Name:"Adam"
};
I then have a function that is designed to extract the relevant image dependent upon an index sent to it.
function SetImage(DeskNo)
{
document.getElementById("DeskImage").src=Person[1].Image
}
This is where I run into problems. The block:
<div class="img>
<script>
SetImage(1);
</script>
<img id="DeskImage" width="30" height="30">
doesn't display anything, but does appear to very briefly flash up an image on loading before clearing it.
This block is repeated, but with an index of 2 and then 3 etc. The idea is that the function can be used to extract and return the image, and display several of them on screen at the same time.
A similar function triggered by 'onmouseover' seems to work successfully, which makes me wonder if the image is being overwritten somewhere, which brings me to my question title. Is it possible to set an src via an element id (in this case 'DeskImage') or otherwise and fix it after the image has been set the first time, even if the src that id points to changes?
I wondered if a direct return of the src from the function may be possible, or alternatively if the index can be automatically appended to the id, however I couldn't identify anything in my searches.
If anyone has any ideas they would be appreciated.

The problem is you are calling SetImage before DeskImage exists. You need to wait until the page is ready before calling your script.
<script>
window.onload = function(){
SetImage(1);
};
</script>
<img id="DeskImage" width="30" height="30">

Related

<img> content: default value

I am new to HTML5 and javascript and I have a question.
I have the following HTML code
<img id='image_preview'/>";
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*'/>
So in short, there is a button, every time I click it, doUpl() is executed. It loads a picture and shows a preview of the picture into <img ... >
the js function is
function doUpl() {
var file = document.getElementById('fileUpl').files[0];
...
dataUrl = canvas.toDataURL("image/jpeg");
document.getElementById('image_preview').src = dataUrl;
...
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg) and the preview of test.jpg already shown when the page is loaded the first time. If the button is pressed the picture is updated.
At the moment, when I first load the html page there is no preview and the input path is empty.
Can anyone help me with this?
Thanks :)
edit: sorry for the confusion. the test img is of course on the server not on the client PC.
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg)
You can do that using the value attribute. Something like this:
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*' value='c:\test.jpg'/>
the preview of test.jpg already shown when the page is loaded the first time.
There are a couple ways you can do this. The basic one is to do like above, using the src attribute:
<img id='image_preview' src='c:\test.jpg'/>"
But, I think is better to do using javascript, because, if one day you need to change this standard image, you only change it on the input element.
</body>
<script>
// self executing function here
(function() {
doUpl(); //this will execute when page is loaded.
})();
</script>
P.S. This is only possible if you have c:\test.jpg on your server
You can check if there is something on the input and fake the img and fake the path but you cannot get a real image from the user hard drive because it's security
If you are talking about preloading images from the client's filesystem, I'm afraid this is not possible due to obvious security reasons:
The specification of the File API states that:
(..) This specification also assumes that the primary user interaction is
with the element of HTML forms [HTML], and that
all files that are being read by FileReader objects have first been
selected by the user (..)

Execute a second function when a first function completes W/O a callback parameter

Background: I'm running A/B tests for a website via VWO. I can write a script that is run when the page loads, but I cannot access any of the website's preexisting scripts or alter their code in any way besides "overwriting" in JS (e.g. remove divs, change CSS properties, append divs) after their page loads.
Problem: When the page loads, there is an empty <div id="priceinfo"></div>. Elsewhere on the page, there is an <img ...>. Inside RequestPriceInfo(), the function outputs HTML to div#priceinfo based on certain form field values on the page. It also appends an "order" button (which is actually not a button at all, but an image nested in anchor tags). I'm trying to change the source for the "button" image using JQuery's attr() function.
Progress: None. I have tried using $('a#requestPrice').click(function() {...} ); but it is not working to change the source of the image, I presume because the content has not yet loaded onto the page immediately when a#requestPrice is clicked and my function runs. I need a way to tell when RequestPriceInfo() has been fired and completed, but there is no callback parameter on RequestPriceInfo() and I don't have access to the script to alter it and add one.
Potentially Useful Info: There is a variable, priceRequested, which is changed from false to true when RequestPriceInfo() runs. Though I realize nothing about this solution is going to be elegant, it seems unreasonable to use Object.prototype.watch() to monitor the variable, but I'm running out of ideas.
How can I detect when RequestPriceInfo() has completed to execute my function without editing the function to add a callback parameter?
What about using CSS... your script could add a class to <div id="priceinfo"></div>, like maybe <div id="priceinfo" class="newButton"></div>. Then, in the CSS, you'd hide the img for #priceInfo.newButton and insert your new image as a background image for the anchor.
Here's one way
var oldRequestPrice = RequestPriceInfo;
RequestPriceInfo = function(){
oldRequestPrice();
// Function completed, handle here
}
EDIT
As the question seems to imply that RequestPriceInfo is an asynchronous API call, have a look at this question: Add a "hook" to all AJAX requests on a page
This will keep track of all Ajax requests happening on the page. You can pick out the one you need and fire your function/code on its success.

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

How to get parentNode ID and use it as a variable

I'm trying to run a script on images within specific blog posts. Each post div is given a unique ID by Blogger that I'm trying to get. Because I only want to run the script on posts containing the function call and not the entire page, I want the function to basically find the ID of the div that's calling it, store that ID as a variable, and then pass that variable in to my function.
<script>
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
</script>
This returns the correct element but the second I wrap it in a function(){} it doesn't work anymore. How can I assign these variables from within a function so I don'thave to clutter up every post's html with a bunch of variable declarations?
Secondly, once I have these variables assigned is there a way to use the value stored with the getElementByID method to actually select the element?
var parentDivID = parentTag.id;
var postID = document.getElementByID(parentDivID); //can't figure out how to select using this as the variable
For ease of use I'd like it if I could simply wrap the function call in script tags and stick it at the end of my post's html whenever I need to use it.
Details
The script I want to run finds images within divs with a specified class and resizes them to fit side-by-side so that the outer edges of the images completely fill the width of the div.
Here is the question covering that script:
Force dissimilar images to equal heights so combined widths fill fixed div
I would like to call this script at the end of any post body where I plan to use side-by-side formatting. The reason I want to call it at the end of a post instead of on the entire page is because the page uses "infinite scrolling" and I'm worried that as posts load after the fact the resizing script will have already been run and newly loaded posts will not be resized.
So I want the function to be able to find the unique ID of the div that contains the call, use that as a variable and ask the script to look inside that post for divs of a certain class, then look within those divs for image tags and resize those images. I hope that makes sense.
Here's an example of what I'd like the post's html to look like:
<div style="width:500px; margin:auto;">
<div class="widthVal x2">
<img class="caption" alt="Caption 01" src="sample01.jpg" />
<img class="caption" alt="Caption 02" src="sample02.jpg" />
<img class="caption"alt="Caption 03" src="sample03.jpg" />
</div>
<script> resizeMagic(); </script>
</div>
Thanks for any help!

How can I retrieve an image path from another page using JS?

This is my case: I have a page with a banner that will be frequently updated, this means the image path of the banner will be different each time the page is updated (can't be overwritten). Anyway, it will be inside a div or container with a constant name.
What I need to do is retrieve that image path and print it in a different page, so if the banner changes in the first page, it will automatically change in the second one.
I thought maybe some javascript could do the work, but I am not really sure how to get the image path from inside the div.
Any help will be appreciated, greetings from Argentina
solution using html5 and javascript is this
you can get the image tag through javascript(as u say it is in div
and whose id you know)
something like
src = document.getElementById("id").childnodes[0].src
should work for u
then you can store this src in the localStorage
localStorage["src"] = src;
as soon as you store something in localstorage it will fire a
"storage" event in all the other pages except the page in which
you have actually stored the src
so handle "storage" event in the other pages like this
window.addEventListener("storage",func,false);
function func(event)
{
src = localStorage[event.key];
//now src has the updated src :)
}

Categories

Resources