Retrieve proper path for dynamic image src assignment - javascript

I understand that there are similar questions out there, but none of them seem to work properly for me. I have a slider and an image. When I change the value of the slider, I want the image to change as well. Here are the relevant pieces of javascript:
var imageArray = ['face0.png',
'face1.png',
'face1.png',
'face2.png',
'face2.png',
'face3.png',
'face3.png',
'face4.png',
'face4.png',
'face5.png',
'face5.png'];
function sliderValueChange(value) {
//$('#painScaleImage').attr('src', '~/Content/' + imageArray[value]); ***gets wrong path
//$('#painScaleImage').src('~/Content/' + imageArray[value]); ***jQuery has no method called .src()
//document.getElementById('painScaleImage').src = '~/Content/' + imageArray[value]; ***gets wrong path
//these are commented out because they all failed to work
}
My images are located in my project under Content/face0.png, Content/face1.png, etc. My Views are located in Views/Home/view.cshtml. The problem is that when I called the $(...).attr() and document.getElementById(...).src functions, the browser looked for the images under /Home/~/Content/face0.png instead of looking under Content/face0.png. The reason I assumed I could use ~/Content/face0.png is because if I were to declare the images in html, this would get the image in the right place <img src="~/Content/face0.png" />. How can I properly achieve what I am trying to do? What is going wrong?

Got it, root relative paths were the correct answer for my solution.
(start the path with a /).

Related

Background-image:URL jumbles the url. when made in JS

In my Js script i tried escaping,setting string to another complete variable and everything i can think of doing.
But cant figure out why the "/ "character in the background-image:url("../") is giving me such a hard time.
Here is a piece of code from my Js script.
let image = "../../" + value.image;
receptenMarkup += '<div class="receptImage" style="background-image:url("../../'+ value.image +'");" alt="test"></div><img src="'+ image + '">';
"../../'+ value.image +'" comes back correctly in the console.log as the path.
Image comes back as the correct path.
Example:
../../images/recepten/thai-chicken.jpg
My console.log of the entire markup also shows a correct path.
<div class="receptImage" style="background-image:url("../../images/recepten/noodle- soup.jpg");" alt="test">
but!! here is the Result in the inspector..
RESULT INSPECTOR:
<div class="receptImage" style="background-image:url(" ..="" images="" recepten="" noodle-soup.jpg");"="" alt="test"></div><img src="../../images/recepten/noodle-soup.jpg">
Notice the image url works great and fine!
The CSS part on the other hand gets all sorts of crazy.
I cant get this to work properly and point the background image to the right path.
I collect a lot of Json data and make cards based on that.
the background image needs to be in a div so i can style it in RWD and not deform like an image tag does.
Somehow i cant get this to work.
Can anyone please give me pointers?
I tried
1: using ../../ to escape ../../ to escape
2: using just "/'value.image'" to go to the root of the website as W3 suggests, no go.
I bee at this for hours now and my deadline is approaching..
Please can anyone explain why the / becomes a space and i get stuff like image=.. in there which i didnt even type that wat.
URL and IMG react differently.
The problem isn't the /, it's the mismatched quote characters delimiting the strings and attribute values.
The simple fix for this is to use a template literal:
receptenMarkup += `<div class="receptImage" style="background-image: url('../../${value.image}');" alt="test"></div><img src="${image}">`;
Side note; I would suggest making all paths relative to the site root, not relative to the current page.

Sharepoint image referencing

I can't seem to find the correct encapsulating or prefix syntax for referencing an image located in xxxx site collection.
Right now I have three variations of one image that will be applied to the footer. And these variants are selected based on the site collection, so I can't directly set the image to the masterpage (Unless I want to make three masterpages, which is just overkill for a single image).
I have tried going about this using Javascript to set the source of an img element and CSS to set the url of a container element's background-image. Both are failing me.
In Javascript, I have tried setting the src attribute of my element to:
"<SharePoint:ProjectProperty Property='SiteUrl' runat='server' />/_catalogs/masterpage/Images/myimage.gif;"
"<% $SPUrl:~sitecollection/_catalogs/masterpage/Images/myimage.gif %>";
"~sitecollection/_catalogs/masterpage/Images/myimage.gif";
and repeated the same with CSS for background-image property to a div element. But all I ever get is errors or it doesn't translate the sharepoint code.
Does anyone have any idea what else I can try?
check these URLs for reference -
http://www.vrdmn.com/2011/08/javascript-lmenubaseurl-varaible-for.html
http://johnliu.net/blog/2012/2/3/sharepoint-javascript-current-page-context-info.html
http://blogbaris.blogspot.com/2013/01/getting-web-url-with-sharepoint-2010.html
and try the below method to get the URL.
<%script type="text/javascript">
var url = "<%= SPContext.Current.Site.Url %>";
</script>
Hope this helps!
Where exactly is this image stored? Is it in the default "Images" library of a publishing site? If so, you've got the wrong path. It would be "/PublishingImages/myimage.gif".

change div background image on click (issues with image path)

On click of a div i am passing an image path to a function and in that function i assign that path to the background-image :url("imagePath").
Somehow the absolute path is being passed and not the actual path.
This is my div
function update(image)
{
$("#divImage")..css('background-image', 'url('image')');
}
but that somehow never worked
can someone please help me on this
$("#divImage").css("background-image", "url("+image+")");
Notes:
1) You have double ..
2) you need + around the variable
Cool.
Edit: people keep editing my posts for no reason - was there any reason to change the ) with full stops?! Bizarre...

images created dynamically do not appear on screen! -> Javascript

I'm trying to do something simple to practice my Javascript (which I learned some recently) and I'm trying to do a game on it (pacman to be precise).
I am trying to build that game board on the browser by creating images dynamically. I've done an array like this:
var images= new Array(25);
for(i=0;i<25;i++)
images[i]= new Array(25);
And, for the game board I used a matrix done with 0 and 1's with 25x25 size (not going to post it here cause is too big and would make my text hard to read) called board.
For the images that I am using right now I have something like this:
var image_empty = new Image();
image_empty.src="Images/empty.jpg";
var image_wall = new Image();
image_wall.src="Images/wall.jpg";
For the initialization function I have something like this:
function drawField()
{
for(i=0;i<board.length;i++)
{
for(j=0;j<board[i].length;j++)
{
if(board[i][j] == 0)
draw(i,j,image_empty);
else if(board[i][j] == 1)
draw(i,j,image_wall);
}
}
}
And for drawing the images themselves I am using this:
function draw(x,y,img)
{
images[x][y] = new Image(22,22);
images[x][y].src = img.src;
images[x][y].style.position = 'absolute';
images[x][y].style.left = 40+x*22;
images[x][y].style.top = 40+y*22;
}
Every time I run this code nothing appears on the screen. I've tried several times use a load of things but nothing happens. I am saving the pictures (at least I think I am) and still nothing.
Can someone give me some pointers of what could be wrong?
PS: Some people pointed me out using the appendChild method would solve the problem, still, since pacman will be moving around I can't use it to store my images (and I was planning to use the draw function to draw anything).
And btw nor Web Developer plugin or firebug point out errors (the code is correct from their perspective).
Creating an Image in the method you describe doesn't actually display the image. Even putting attributes and styling to make it appear a certain way doesn't add it to the DOM. The advice about append child is correct. For example, if you had:
<div id="main"></div>
and you called
document.getElementById("main").appendChild(images[x][y]);
this would insert the image inside the div. You could do this repeatedly to generate the equivalent of...
<div id="main">
<img src... />
<img src... />
...and so on
</div>
Then, your CSS styling and positioning would work.
There's nothing wrong with your script, but Firebug does display a rendered version of the DOM. As you run the script, you will actually see the HTML tab of Firebug changing with the images you've added to the page.
Also, keep in mind that the DOM must complete loading before you are able to run this. You can accomplish this by doing a simple:
<body onload="drawImages()">
UPDATE: Once you've actually added the 25x25 images, the array still references the elements - they're just now part of the DOM. So, you can change their source via:
images[x][y].src = "newImage.jpg";
If you, for some reason, wanted to remove an image from the board, leaving a gap, you can remove it from the DOM
document.getElementById("main").removeChild(images[x][y]);
or just hide it via CSS.

Relative paths of images in JavaScript

I have a javascript module which creates a div with a picture of a close button ("X").
This div and javascript are placed in many places on my site.
Relative path solution: When a page includes the javascript, and the javascript uses a relative path for the image. The relative path is relative to the HTML-page. If HTML pages in different paths use this javascript I will need 2 different images.
Absolute path solution: I do not know what server my team-member is using for development (I know for sure that he is not developing on my server). This means that absolute paths will not work.
Is there a simple way of overcoming this problem? Like making the script somehow aware of its path?
Mutable paths (test/staging/production domains) is always a problem in javascript, the best option is to include the root path of your application/website in the HTML. The obvious place to do this is in your template layer. For example:
<body data-root="${rootContext}">
<!-- or whatever syntax your template layer uses -->
And grab it with javascript for usage in your scripts.
var rootContext = document.body.getAttribute("data-root");
Note, you can only do this when the DOM is ready (or when document.body is available, differs cross browser) ;)
An alternative and in my view less pretty option is to simply render javascript.
<script>
var rootContext = ${rootContext} // or whatever syntax your template layer uses.
</script>
At least with the 'data-root' technique, you can store the value wherever you like and avoid a global definition.
So in your code where you reference an image, you can do the following:
img.src = rootContext + "/media/js/close.gif";
Or create a nice helper method:
// lets use a namespace to avoid globals.
var myApp = {
// still need to set this when DOM/body is ready
rootContext: document.body.getAttribute("data-root"),
getContext: function( src ) {
return this.rootContext + src;
}
}
img.src = myApp.getContext( "/media/js/close.gif" );
In the helper method, you can also write some code to ensure proper uses of / and whatnot.
There are three ways to specify a path to an image in html:
Completely relative: <img src="kitten.png"/>
Absolute with regard to the filesystem, but relative to the current server: <img src="/images/kitten.png">
Absolute in all respects: <img src="http://www.foo.com/images/kitten.png">
The second method may work for you.
Can't you just use a CSS class? If it's just a div containing an img, you can get rid of the img and use background-image on the div. Setting this from CSS will make sure that the image path is always relative to the CSS file and will almost certainly work no matter the environment (as long as the other images in your CSS work).
Then, you can just set the className on your div accordingly.

Categories