the releative path in javascript - javascript

I meet some problem when locate the resources such as css js img in the page.
For example,I want to use a javascript lib:dtree,it contain some built-in images and css.
This is its structure:
img
dtree.css
dtree.js
example.html
The exmaple.html is a live demo to show how to use dtree. It use the dtree.js as:
<script type="text/javascript" src="dtree.js"></script>
Now I create a new folder,and copy the example.html here,and modify the src of the js:
<script type="text/javascript" src="../dtree.js"></script>
Now,this is the new structure:
img
dtree.css
dtree.js
example.html
chd
--example.html
When I browser the chd/example.html,some required imgs are missing.
And in the dtree.js,there are some codes like:
this.icon = {
root:'img/base.gif',
....
}
So I think the img here are not based on the dtree.js but the current page which call the js.
If so,I think I am fxxked.
I have to put all my pages to the same directory with the img(it contains the required imgs by dtree.js) if I want to use the dtree.js?
And solutions?

you need to adjust image root path by adding slash before img like:
this.icon = {
root:'/img/base.gif',
....
}

Related

Export HTML containing MathJax results

I use QWebEngineView to convert Markdown to HTML and render the math formula via MathJax. All the content are inside a <div id="placeholder">. Then I use document.getElementById("placeholder").innerHTML to get the HTML content, which contains the converted Markdown content and rendered MathJax output. At last, I output the HTML content to a HTML file.
However, when I open the exported HTML file via Chrome, the formulas lose the CSS styles like this demo.
So any idea to make the formulas in order?
I have tried to add MathJax script to the exported HTML but the formulas will disappear.
Thanks!
You need to grab not only the HTML, but also the CSS that MathJax's CommonHTML output jax produces, and the styles for the AssistiveMML extension (since your copied HTML includes its output as well). The code below will obtain it for you.
<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function () {
var styles = document.head.getElementsByTagName("style");
styles = [].slice.call(styles); // convert to array
while (styles.length) {
var sheet = styles.pop();
if (sheet.innerHTML.match(/^(?:.mjx-chtml|.MJX_Assistive_MathML) \{/)) {
document.getElementById("sheet").innerHTML += sheet.innerHTML;
}
}
});
MathJax.Hub.Queue(function () {
var math = document.getElementById("math");
math.parentNode.removeChild(math);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/MathJax.js?config=TeX-AMS_CHTML"></script>
<span id="math">\(x\)</span>
<pre id="sheet">
</pre>
Put this into a .css file an link that to your page (or put it into a <style> tag in the document head). That should do it for you.
Include the MathJax script in your HTML file:
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML'></script>
For some reason, the content is faded out and gets hidden, so the following styling is needed to stop the content from being hidden:
<style>
.MJXc-processed {
display: block !important;
}
</style>
You can add that inside the HTML file's head

Grab images from JSON file with NodeJS

I am testing an Electron app. I want it to grab images from this website. That website has a JSON file that has this code.
How can I get those images and put them in an img tag?
So far I have this code:
var request = require('request');
request("http://www.pgbovine.net/photos/json-files/boston.json" , function(error, response, body) {
body = JSON.parse(body);
console.log(body);
function addImg(arr) {
myImg = arr[0]["filename"];
var theImg = document.getElementById("image");
theImg.innerHTML = myImg;
}
And this HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pics</title>
</head>
<body>
<img id="image">
<script type="text/javascript">
require("./memes.js")
</script>
</body>
</html>
The problem is, that code doesn't do anything! So how can I grab an image from the JSON file above and put it into and img tag? (Using NodeJS or vanilla JavaScript)
You are simply adding to the img tag the filename, but you need to add the entire image url not just the filename (like IMG_2914.JPG).
I tried http://www.pgbovine.net/photos/IMG_2914.JPG but got 404 error.
You should be modifying the 'src' attribute of the img html tag to point to the URL or relative path of the image in question.
You would call the 'setAttribute' method on theImgvariable to do this.
Based of the structure of that JSON response, you may also want to set the 'alt' attribtue to the 'description' string of each image object, which would provide a simple mouse-over text.
Note that the JSON that you're talking about here doesn't actually contain the image, just a string that is the filename of the image.
Based on the website you seem to be attempting to scrape, to grab things from the boston image gallery, you would need to append the filename to the following string:
http://www.pgbovine.net/new-galleries/boston/images/
Like so:
<img src="http://www.pgbovine.net/new-galleries/boston/images/IMG_2914.JPG">

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

Manipulating html page by .js file

I have successfully called the following JavaScript code to populate an image and description using parameters.
The image and description are in tags and are called imagePlaceHolder and descriptionPlaceHolder. As I say, this works perfectly.
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
PlaceHolder.innerHTML=descriptiveText;
}
What I now require is to place the javascript in its own file and call it from the HTML page using <script src="xxxx.js"></script>
The problem is that the object in the <div> is not recognized. I need to amend the line
document.getElementById('imagePlaceHolder');
to point to the HTML file containing object to manipulate.
Can anyone advise me of the correct syntax please?
In the HTML file you need to link the javascript file in the header
E.g.
<head>
<script src="/scripts/yourjavascript.js" type="text/javascript"></script>
</head>
then do a onload function at the top of your javascript file
window.onload = function(){
changeImage("imgName", "descriptiveText");
}
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
text.innerHTML=descriptiveText;
}
any javascript using document should reference the html document

Having trouble loading a javascript (images don't load)

I downloaded a calendar javascript. My working directory is /user. I put the script into /user/js/calendar. In my HTML located at user/, I have...
<script language="JavaScript" src="js/calendar/calendar_us.js"></script>
<link rel="stylesheet" href="js/calendar/calendar.css">
The .js and .css load, and I see the calendar form, but the images under user/js/calendar/img do not load when it's displayed on the browser.
The image reference code in the downloaded javascript is below
<img src="' + this.a_tpl.imgpath + 'next_year.gif" />
this.a_tpl.imgpath is 'img/'. Is there something I need to add or modify in my HTML or in the .js file to make correct relative reference to the files in user/js/calendar/img?
The image tag is trying to load the image from /user/img/next_year.gif. Either move the images there, or add the path to the code:
<img src="js/calendar/' + this.a_tpl.imgpath + 'next_year.gif" />
Note that image tags will load images relative to where the page was loaded from, while images used in a stylesheet will load images relative to where the style sheet file was loaded from.
You can't put javascript string functions directly in your HTML like this:
<img src="' + this.a_tpl.imgpath + 'next_year.gif" />
You can use a piece of javascript to document.write() the image tag inline or you can create the tag dynamically in javascript and set the .src property using JS after the document has been loaded. But, you can't just throw some javascript into the middle of your HTML like this.
For static definitions of image URLs in an HTML file, the paths should either be relative to the page location or they should be relative to the top of your domain or they should be a fully qualified domain/path.

Categories

Resources