I'm using JQuery to switch out an image src thusly:
$("#myImg").attr("src", "../../new.gif");
notice the relative pathing on the new src. Unfortunately, this isn't portable when I deploy my app. In my MVC app I'm using a ResolveUrl() method that will fix the pathing problem for me so it's portable, but now my JQuery image src swapper doesn't work right since it now switches the correctly resolved path to a broken relative one.
<img id="myImg" src="<%=ResolveUrl("~/Images/transparent.gif")%>" />
What I want is for JQuery to just flip the actual filename and leave the path untouched. My first thought would be to
// pseudocode javascript jquery on my thought on how to approach this prob
var oldFullPath = $('#myImg").GetTheImgSrc;
var newFileNameWithPathIntact = someRegexAddNewFileNameWithOldPath
$("#myImg").attr("src", newFileNameWithPathIntact);
but that seems rather gross and un-JQuery to me. Anyone got a better way?
you could use something like this:
var oldImage =$("#myImg").attr("src");
var imagePath = oldImage.slice(0, oldImage.lastIndexOf("/")) + "/new.gif";
$("#myImg").attr("src", imagePath );
EDIT: better code...:)
You can use the resolveurl right in the javascript:
$("#myImg").attr("src", "<%=ResolveUrl("~/Images/new.gif")%>");
That of course assumes that you've included the javascript right in the view. If you have a requirement that this script must live in a separate script file from the html request, then you can just have a view which is a javascript file ... and just reference that URL in the script src:
<script language="javascript" src="<%= Url.Action("MyMethod") %>" />
why not just use a variable for the root of the app that you can use for these types of situations.
var root = "<%=ResolveUrl("~/") %>";
Now you can easily construct your image path
$("#myImg").attr("src", root + "images/" + fileName);
Related
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
I am trying to get standard path with javascript for images in my project
I used src for image as below
document.testImg.src = '../Images/test.png';
Do we have any option like below to make path consistent?
document.testImg.src = '#Url.Content(~/Images/test.png)';
<img name="testImg">
Thanks in advance
As you probably know you can't use Razor in Javascript unless that script is part of the Razor view. It's not the "sexiest" way but one way out is to have a "global" javascript URL variable in your Layout View/MasterPage.
for example in your shared layout you'll have a variable:
var AppUrl = '../Content/Images/';
so then in all your views you can use this consistent variable:
var myImageUrl = AppUrl + 'image.jpg';
p.s. Don't want to use variables ? Stick a function in your shared view instead:
For example in your shared layout you'll have a function:
function AppURL(url)
{
return '../Content/Images/' + url;
}
so then in all your views you can use this:
var myImageUrl = AppUrl('image.jpg');
I found a good solution for this. I used t4mvc for my project and updated all my magic strings. I thought this solution would be useful for few developers who have issues with paths.
This way we can use Url.Content() few example code i added that may help others.
<p>This link goes to my ``Application home page.</p>
<p>Now let’s link to a view ``in the Controller/Action directory.
Url.Content("~/img/myImage.png")
<img src= "#Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>
I found the answer to my question via a simple Google search, although, there is a slight problem that I ran into.
So far, I have an image on my HTML page with the ID of newAvatar. I am attempting to find this image via its ID, and save it's source into a variable, then eventually into an XML document to be used later on.
When I save this source into a variable, or alert it for checking purposes, it is displaying the full source, which is unusual. For example, I am running my site on a WAMP server, so the variable is saving as:
http://localhost/uploads/newUploadedImage.jpg
When in reality, the source should be plain and simple, uploads/newUploadedImage.jpg
The image tag is
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;" id="newAvatar"/>
The way i am checking the source is
alert(document.getElementById('newAvatar').src);
Any idea how to get rid of the first lot of junk?
All help is greatly appreciated!
By using #DavidThomas comment before, I managed to get it working. This is what i changed my alert to:
alert(document.getElementById('newAvatar').getAttribute('src'));
var hostname = document.location.hostname;
var url = 'http://' + hostname + '/';
var src = document.getElementById('newAvatar').getAttribute('src'); //'uploads/newUploadedImage.jpg'
var image = src.split('/')[1];
console.log(url);
console.log(image);
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;"
id="newAvatar"/>
and
$(function()
{
alert($('#newAvatar').attr('src'));
});
I want to assign different background images to a div depending on the page's address, so for example, if my url is http://www.mywebsite.com/mysubdirectory/ I use the following code:
if(document.URL.indexOf("mysubdirectory") >= 0){
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
}
But it's not working. I even added a bogus document.write command just to make sure the rest of the code was ok and sure enough the bogus line showed up in my browser. Is there something I'm overlooking?
EDIT: Thank you all for your answers - when I use body instead of getElementById("wrapper") in my code, the image shows up, so I doubt it's a path-related issue. I trued adding an onload attribute to the body tag but it's still not working with getElementById. Any ideas?
Your
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
code is correct.
It works fine in this jsfiddle: http://jsfiddle.net/hUuN5/
Are you sure the image is correct. Remember that the path to the file is relative to the location of the current page. NOT the css directory
I'm using Chrome 29.0.1547.66 and none of the anwers worked either.
So I tried:
document.getElementById("wrapper").style.backgroundImage = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
It worked taking off the quotation marks from the image url.
Here working as well: http://jsfiddle.net/xEujg/
html css backgroundimage javascript
Try this, I think the image url is wrong most likely. You probably need a relative path of sorts:
document.getElementById("wrapper").style.backgroundImage = "url('/bg-wrapper.jpg')";
Specifying a protocol worked for me in chrome. I couldn't get it to work using the catch all '//'. It had to be 'http://' I'm assuming it must match whatever protocol was used to load the page or iframe.
for example
element.style.backgroundImage="url(http://somedomain.com/images/myimage.jpg)"
or
element.style.backgroundImage="url('http://somedomain.com/images/myimage.jpg')"
worked for me.
If anyone is still interested in this. Here is a solution:
document.getElementById("wrapper").style.background = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
This works for me:
var pointer = "url(\'/" + imageArray[imageCounter].toString() + "\')";
document.body.style.backgroundImage = pointer
After spending a bit of time on this, it was the browser's engine parsing the CSS. No good errors in the console.
The solution is to not do everything on the same line.
You have to create a variable, assign it the url and then pass it.
let bg = "url('" + imgUrl + "')";
document.getElementById("wrapper").style.backgroundImage = bg;
I'm pretty new to JavaScript and am wondering how on a page with links to images, i.e. http://www.example.com/image.jpg I can get them to be changed automatically by JavaScript to be embedded, ie with <img> tag
Hope that makes sense!
Thanks
We're particularly fond of the jQuery framework here, as it makes this sort of task very easy. With jQuery on your page, you can easily do this:
$(document).ready(function() {
$('a[href$=.jpg]').each(function() {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc);
$(this).replaceWith(img);
});
});
This will work specifically for <a> tags whose href attributes end with .jpg You can expand it to other file extensions, of course, but to dynamically determine whether a link leads to an image if the URL is not obvious would be a far greater challenge.
Do you mean convert all image url's to hyperlinks "pointing" to the images?
var x = document.getElementById('body');
x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'$1/');
I haven't tested this, but it should work. No third-party frameworks are needed.
From here