import image with Javascript to jsp - javascript

On my JSP I was using:
<img id="sharkgraphic" src="<c:url value="/images/fcs1.svg"></c:url>"/>
otherwise the browser could not find the svg file. Now I want to be able to set the src in javascript.
I tried using:
var sharkurl = require("../images/fcs1.svg");
$( "#sharkgraphic").attr("src",sharkurl);
How would I properly set the source of that img ?

It depends on deployment setup of your application.
c:url without context attribute is resolved to {context of app}/{value}, e.g. if your app deployed to
http://localhost:8080/my-app
then
src='<c:url value="/images/fcs1.svg"/>'
be resolved to
src='/my-app/images/fcs1.svg'
in this case
$("#sharkgraphic").attr("src","/my-app/images/fcs1.svg");
should work fine

Related

Loading a var from window global into React App not working

I know there are lots of answers to this. My purpose is to have a js file that I can use terraform to inject into a docker image so I can easily change the client logo during deployment and have a single docker image for my react ui. I have tried the solutions in the following answers:
how-can-i-pass-a-variable-from-outside-to-a-react-app
how-to-include-external-javascript-in-react
external-javascript-is-not-working-in-react-js
react-accessing-a-var-from-a-script-in-a-component
The simplest method seems to be to import a script in head in index.html, with the var declared therein. I have the following in my index.html and env.js is in the static folder where other js files (plotly) are loaded successfully.
...
<script src="http://localhost:3000/env.js"></script>
</head>
I have the following in env.js
window.logo_file = '/images/demo.jpg';
Then in my React component I have:
<div className={'clientsLogo'}>
<img
src={window.logo_file}
alt={'client-logo'}
height={61}
style={{ verticalAlign: 'bottom' }}
/>
</div>
I also tried adding export default logo_file using logo_file = '/images/demo.jpg'; in env.js.
I tried assigning the window.logo_file to a const prior to using it.
But the imported script does not have it's variable added to the global window object and it escapes me why not.
The answer is that the env.js, i.e. the file with your window global variable declared, has to go at the top of the head section of your index.html file to be loaded before the react app is loaded.

JS source not visible in Chrome/Firefox debuggers, but correctly loaded in the page

I have a web page which does navigation using templates and filling / showing them depending of user interactions.
It works quite well, but the templates contains some JS included with them. This JS code is correctly loaded (in the example below, it provides an alert saying "Hi") when the page is just loaded. However, I don't see the code within the debugger console, either in Chrome or Firefox.
I've provided a minimal example below, where I see in the console > Source, under localhost, only my HTML page and jquery.min.js in the asset/js sub-folder.
Here is my HTML :
<script src="assets/js/jquery.min.js"></script>
<template id="my_screen">
Hello
<script type="application/javascript" src="assets/js/testouille.js"></script>
</template>
<section class="container">
<div class="my_screen hide"></div>
</section>
<script type="application/javascript">
function useTemplate(elem) {
var myTemplate = $('#' + elem),
normalContent = $('.' + elem),
clonedTemplate = myTemplate.html();
normalContent.empty();
normalContent.append(clonedTemplate);
}
$(document).ready(function() {
useTemplate('my_screen');
}
)
</script>
And here is my Javascript :
alert("Hi");
Any idea?
Since testouille.js is in a <template>, it's not loaded automatically by the browser when the page is loaded.
When you clone the template and append it to a regular DIV, jQuery emulates loading the file using $.getScript(). In the Chrome debugger, code that's loaded this way will be shown in a VM:#### filename (where #### is an arbitrary number) in Sources, rather than with its actual filename.
You can make the debugger give this a filename by putting the following comment in testouille.js:
//# sourceURL=testouille.js

How to go up one level in javascript (when using Ajax.open) [duplicate]

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

img is not loading when change the image by using javascript

This is my code i can't understand what is wrong with in this.
<html>
<body>
<script type="text/javascript">
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "C:\Users\ashokch\Desktop\light_bulb_off3.jpg";
} else {
image.src = "C:\Users\ashokch\Desktop\bulbon.png";
}
}
</script>
<img id="myImage" onclick="changeImage()"
src="C:\Users\ashokch\Desktop\light_bulb_off3.jpg" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
</body>
</html>
Default image is Displaying when page come in browser but when I click the image changing image is not loading
You aren't using valid file protocols (file:///C:/mydir/index.html) to access the files. As others have said, move them "next" to your html file and just use the file name without a path (e.g. light_bulb_off3.jpg), or change your paths to something valid (e.g. file:///C:/Users/ashokch/Desktop/light_bulb_off3.jpg)
Try this:
<img src="file:///C:/Users/ashokch/Desktop/light_bulb_off3.jpg">
Please notice the file:/// protocol handler. And / (slash) instead off \(backslash).
It is used to show local files in your browser.
But this only works for local files.
If you want the webserver to serve these images, create a folder in your webserver root folder.
Example
/images
And store your images in that folder.
Then point your image src or javascript attribs to the absolute path.
<img src="/images/my-image.jpg">
This will take your current url, strip out the hostname and protocol and append the src.
Example
http://www.example.org/folder/test.html
<img src="{http://www.example.org}/images/my-image.jpg">
<img src="{http://www.example.org/folder/}images/my-image.jpg">
<img src="http://www.some-image-host.com/xyz123.jpg">
Absolute means, with protocol and hostname/path.
Relative means, relative to the root of your current domain (without any path).
Upload your images to a free image hosting website like :-
http://photobucket.com/ or
https://imageshack.com/
Use the new weblinks to the images & check if it works.
"bulbon" ??? What's it ?
Your image path should be relative to your project/code directory instead of the file system. Either copy the images into the project directory or give a relative path. That would solve the issue.

Changing image src with javascript with an variable in it

I made an template in HTML and now i am putting it in as an wordpress template. But in my .js file i got this:
$('.tab_home').find('img').attr('src', '/images/home.png');
This is part of an click function and changes the image when i click on something. And it works fine in HTML but when i want to put this is in wordpress it is broken because the src url is wrong ofcourse. Now i did find this thread: WordPress path url in js script file and this would be part of my solution except that i can't put "+templateUrl+"in my .attr('src', '/images/home.png')Cause then i get an link like:
<img alt="" src=""+templateUrl+"/images/home.png">
Does some1 know what im doing wrong here, and how to fix it?
Thanks in forward.
You must do it as follows:
$('.tab_home').find('img').attr('src', templateUrl + '/images/home.png');
And don't forget to set templateUrl in the header of the template, as described in post you're referring to:
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

Categories

Resources