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
Related
I am trying to complete an exercise for one of my courses and my HTML file won't link with my Javascript file. I put the link between my HTML file and my Javascript file in the body of my HTML file but the files still won't connect. When I test this code in Microsoft Edge, the buttons simply do not work. Anybody know what the problem is?
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<button onclick = "startWorker()">Start Worker</button>
<button onclick = "stopWorker()">Stop Worker</button>
<ul id = "output">
</ul>
<script type = "text/javascript" src = "/js/script.js"></script>
</body>
</html>
Javascript
var worker;
function startWorker(){
worker = new Worker ("js/mod4_worker.js");
worker.onmessage = function(event){
document.getElementById("output").innerHTML += '<li>' + event.data + '</li>';
};
}
function stopWorker(){
worker.terminate();
}
Files
So, I would try my comments :
Change the script.js path to : "../js/script.js"
Change the worker passed script to "../js/mod4_worker.js"
As GGG said, using a path starting with "/", a slash, use the path from root. The full path is either :
Windows : file://DriveLetter:\REST_OF_PATH
Unix/Linux/OSX : file:///REST_OF_PATH
WebServer : http://domain/REST_OF_PATH
If the structure is from /webapp/ :
html/index.html
js/script.js
Accessing script.js from index.html needs to go back one folder (..) and then set the path seen here (js/script.js) which gives (../js/script.js) OR using full path (/webapp/js/script.js) which I wouldn't recommend because if you change "webapp" directory of location or URL (on WebServer)
Remove the / from your src in the index.html. So it should be
src = "js/script.js"
Why? When you begin the src value with a /, that means you're referring to an absolute path (in other words, it starts the path from your drive's root). My devtools shows it as
file:///C:/js/script.js
By removing the first / in your src, you're now doing relative pathing, and it will look in the correct place.
Permissions & File locations
(Stumbled on this Q and here's the only way I solved it...)
For me, I found it was a permissions and file location issue...
I'm running a local webserver on Ubuntu 18 Desktop, working with dev from a local folder linked to the web directory: /var/www/html/MY_DEV -> /home/me/MY_DEV. So, the www-data user couldn't actually "own" them like it needed to.
I use this setup just fine for PHP, HTML, and CSS just fine. But, if I include a javascript file via src="", no matter what I do, it doesn't work.
The only way I could get it to work on my desktop is if BOTH the served file (somefile.php or somefile.html) are physically at /var/www/html/...
And, of course accessing them at localhost/...
And, of course owning them obsessively with sudo chown -R www-data:www-data /var/www/html
I want to use handlebars on the client side. In my html code I have calls like:
<img src="data/cloud/products/{{key}}/{{images.product.frontal.trans_bg_img}}" alt="">
directly in my index.html.
In javascript I do something like this:
this.emptyPageSource = $("#productdetail").html();
this.productTemplate = Handlebars.compile(this.emptyPageSource);
var html = this.productTemplate(product);
$("#productdetail").html(html);
which works fine. I take the existing piece of html from the dom as a template once, then apply the templating with handlebars and overwrite the old dom entry.
When I load the page, I get a lot of 404 requests, because the browser already tries to load the image resources, even if the templating wasn't invoked yet, due to the JS part.
Is there a way to evade the 404 get requests? (I'm not using angular or something alike - just plain js + jquery)
Thank you in advance
Chris
I will try converting #productdetail element to <script type='text/template' id='productdetail'>. As in: JSBin
<h1>A Cat</h1>
<script type="text/template" id="productdetail">
<img src="{{image}}" alt="">
</script>
Rest of it
<script>
var product = {
key: '1',
image: 'https://media.giphy.com/media/freTElrZl4zaU/giphy.gif'
}
var emptyPageSource = $("#productdetail").html();
var productTemplate = Handlebars.compile(emptyPageSource);
var html = productTemplate(product);
$("#productdetail").replaceWith(html);
</script>
The browser does not understand text/template scripts and just ignores its. But we can read the content inside our script tag use it as a template.
this code is not working as expected
<html>
<head><title>alert()</title>
<script type="text/javascript">
function greeting()
{
var name=prompt("what's your name?","your name");
if(name){
alert("hi, " + name + " welcome to this page");
document.getElementById("im").src="F:\wallpapers\a.jpg";
}
}
</script>
</head>
<body onload="alert('hi, this is the alert() function');">
<img id="im" src="F:\wallpapers\Ubuntu_wallpaper__1_by_leroi14.jpg" onclick="greeting();" /></body>
</html>
document.getElementById("im").src="F:\wallpapers\a.jpg" is not displaying the image when given absolute path.
But it works if image is in same folder as this file.
can anyone help?
For whatever reason you use backslashes in your path, which need to be escaped in string literals:
"F:\wallpapers\a.jpg" === "F:wallpapersa.jpg"
Use "F:\\wallpapers\\a.jpg" or "F:/wallpapers/a.jpg" instead.
If you plan on serving this page to others, you don't want to use an absolute path. Javascript runs on the browser, and does not have access to the server's filesystem for absolute paths.
See answers here
It's common to have an images folder within your website's project folder. Put images in this folder, then you can use src="/images/a.jpg"
I have the following implementation of bigvideo.js functioning perfectly outside of my Rails project.
<script src="modernizr.js"></script>
<script src="jquery-1.7.2.min.js"></script>
<script src="jquery-ui-1.8.22.custom.min.js"></script>
<script src="jquery.imagesloaded.min.js"></script>
<script src="http://vjs.zencdn.net/3.0/video.js"></script>
<!-- BigVideo -->
<script src="bigvideo.js"></script>
<script>
var BV = new $.BigVideo();
BV.init();
if (Modernizr.touch) {
BV.show('yay.jpg');
} else {
BV.show('test.mp4',{ambient:true});
}
</script>
However, when I try to translate this to Rails, it will not render either the image or the video.
- I have all javascript files in assets/javascripts. They appear to be pulling correctly.
- Application.js is untouched and includes //= require_tree .
- For the custom JS (the one where the js code is displayed above) I currently have it as a JS file in assets/javascripts. I've tried putting the relevant image/video files in the folder with it, changing the paths to web addresses for the files, and naming it .html.erb and using ruby snippets, all with no success.
How can I make my implementation work? You can see it working outside of Rails here.
I was able to get BigVideo to work with rails. I'm not sure if this is the most ideal fix, but if you give the full url for the video (via something like <%= request.protocol + request.host_with_port + asset_path('main-video.mp4') %>) it will load on the page.
So the code I ended up using in the end was:
<script>
$(function() {
var BV = new $.BigVideo();
BV.init();
BV.show("<%= request.protocol + request.host_with_port + asset_path('main-video.mp4') %>",{ambient:true});
});
</script>
I've set up an example app that you can take a look at. It's located here (note: I tried to remain somewhat faithful to your onepager example, but it's not exactly the same):
http://bigvideo.herokuapp.com/
You can also see the code I used to create it here:
https://github.com/scouttyg/bigvideo-example
I also did some fun stuff like put the video in its own directory (assets/videos), and added the precompiled paths to application.rb as well.
I think the idea is in general, you should use BigVideo with a CDN and not serve it up from the rails app itself -- similar to why it's suggested in rails to offload file uploading to things like S3, etc.
if js working properly your files would render properly in case you put them into app/assets/images directory and include them into js like below
BV.show('assets/yay.jpg');
} else {
BV.show('assets/test.mp4',{ambient:true});
Another way:
Add these (required) lines of code to your application.html.erb file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/5.11.3/video.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/BigVideo.js/1.1.5/lib/bigvideo.js"></script>
and then the code Scott included above
<script>
$(function() {
var BV = new $.BigVideo();
BV.init();
BV.show("<%= request.protocol + request.host_with_port + asset_path('main-video.mp4') %>",{ambient:true});
});
</script>
...and then eventually decide to do it a better way, because this will get things working at the very very least.
I want to have an image in a webpage that can be changed based on the filepath stored in a file online (it doesn't matter what typer of text file - xml, .txt - whatever works best).
So I basically want to have the page retrieve the text from that file, and then use that text as the source for an image in that page.
I'm assuming this is a Javascript thing, but it doesn't matter to me, as long as it works.
Any ideas?
Thanks!!
**Edit: Forgot to mention: I'm using the code in a Google Chrome Extension, not sure that matters, as it uses regular HTML/Javascript, but it's stored on the users computer, and I want the image to be stored on my server.
**Edit2:
Just got something that seems to work very well, and I only need this in the body part of the code:
<script type="text/javascript" >
var i=0;
for (i=0;i<=FilePath.length - 1;i++)
{
document.write('<img src="' + FilePath[i] + '"/>');
}
</script>
Hope this is valid code, but it definitely seems to work here...
Its simple store the filepaths in a Javascript file , create an array in the JS file , and include all the filepaths in the array, then store the file on the webserver .
Then after that you can retrieve it using
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
After you retrieve it , you can use Javascript , I prefer jQuery , to replace the src attribute on the Image with the one from the array .
EDIT : Full version :
//Javascript web server File
var FilePath=new Array("Path1","Path2","Path3");
Create a file like this and store as many paths as you want in the array .
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
<script type="text/javascript" >
$(document).ready(function()
{
$('#DisplayImage').attr('src',FilePath[0]);
});
</script>
</head>
<body>
<img src="" id="DisplayImage" />
</body>
</html>
This is a simple example , you can try learning javascript and Jquery to tweak it further .
Since my php based answer was not applicable, we can all ignore it now. :)