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

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.

Related

How can I add an eventListener to an image inside of an external js file?

I have an index file that appends an external javascript file (a file generated from a game creator). I am trying to check if the images inside that javascript file are loaded so that I can remove the preloader by adding the class ".loaded" to the body. I cannot find a function that allows me to do this. I've tried .load, onLoad, document.ready, etc. I thought window.onload only executed after all dependent resources were also loaded (the images) but it is firing after the appended javascript file is loaded but before the images have.
Sample code:
<body>
<!---PreLoader--->
<div id="loader-wrapper">
<div id="loader"></div>
</div>
<div id="content">
(Modernizer code here that appends the js file, using function below)
jQuery(function () {
$('body').append("<script src='" + widgetName + ".js'></script>");
}
</div>
One option I tried that fired before images:
$(document).ready(function() {
$('body').addClass('loaded');
});
Thanks in advance for any help.

How to include simple JavaScript within Hugo

Given the following code:
$('img').mouseenter(function(){
//...
}).mouseleave(function(){
//...
});
I'd like it to be included in my articles. I'd like to avoid editing the theme if possible so to avoid forking etc.
This depends a little on which theme you use. This may be an area where we could do a better job, but do this:
In the theme, look in the
layouts/partials folder.
If you find a header.html or similar, copy this to your local layouts/partials. You can then override the content of this file only. Alternatively you can customize by copying the template used for single pages, often: layouts/_default/single.html.
bep's answer is excellent, but here are some additional details for hugo/frontend newcomers like me
1. Find a place in your HTML where to include the JS
First, one should copy the header.html or footer.html (or similar) of the Hugo theme to your layouts/partials folder. It does not necessarily have to be the header or the footer, but a file that is included in every page on your html (and that's why you would typically use the header.html or footer.html).
I got a theme that had the footer at <theme_folder>\layouts\partials\_shared\footer.html, which I then copied from the theme folder into the project layout folder <project_root>\layouts\partials\_shared\footer.html.
2. Include the script.js in the HTML
Then, I added to the bottom of footer.html
<script defer language="javascript" type="text/javascript" src="{{ "/js/myscripts.js" | urlize | relURL }}"></script>
The defer attribute can improve the page loading time a bit, and "/js/myscripts.js" is the location of my javascripts. The location is path relative to <project_root>\static\. Here are the documentation about relURL and urlize.
The example script file contains just
// myscripts.js
function myFunction(x) {
let d = new Date();
alert("Current datetime: " + d + "\nYou passed in: " + x);
}
3. Use the JS function
This is an example of using the JS function from within Hugo template (any .html belonging to the template):
{{ $somevar := "spam"}}
<button onclick="myFunction( {{ $somevar}} )">Click me</button>
Inline JS
It looks like also inline JS runs just fine; for example, adding
<script>
alert("Script loaded!");
</script>
to a template html file ran just fine. I would use this only for quick testing though, since some scripts might be needed in multiple html files, and adding the same script to multiple files would just increase your overall website filesize.
I copy themes/whatever/layouts/_default/baseof.html to layout/_default/baseof.html and add the following block at the end of the html tag:
{{ block "page-script" . }}{{ end }}
Then I can add
{{- define "page-script" -}}
<script>console.log("Hello!")</script>
{{- end -}}
in my layouts files to put in a script.

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.

CSS stripped from content embeded via Javascript into Div

I have the following file file:
<html>
<head>
<title></title>
<script type="text/javascript" src="/Prototype.js"></script>
<script type="text/javascript">
function load_content()
{
new Ajax.PeriodicalUpdater('content', '/UpdatedContent/,
{
method: 'post',
frequency: 5
});
//var fileref = document.createElement("link");
//fileref.setAttribute("rel", "stylesheet");
//fileref.setAttribute("type", "text/css");
//fileref.setAttribute("href", filename);
}
</script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
load_content();
</script>
</body>
</html>
Content from UpdatedContent is supposed to be loaded into the "content" div every 5 seconds. What's weird is that the HTML is loaded but the section at the top of the loaded page is completely stripped out when it gets inserted into "content"
The loaded page is essentially this:
<style type="text/css">
... lots of css here ...
</style>
... lots of HTML here ...
There are no , ,
Can CSS not be injected directly into a div?? Is there some reason either the Prototype framework or the browser's DOM is stripping out the CSS?
How can I include the CSS without making a separate call??
As you can see from the given main file, the page would be completely blank without anything loaded in the "content" div. This is intentional. I am basically wanting to use this as a structure on which to dynamically load updating content on an interval, so that the page doesn't have to completely reload to do a refresh of the data.
And no, I can't just hard code the CSS into the above file as the CSS will be changing too.
Edit: Regarding yaauie's response... now I know why it's happening, since I'm passing style and content in one single piece. If I separate the CSS into a separate file that can be loaded, how would I then load this via AJAX (preferrably using Prototype) and then, more importantly, set that CSS as the style sheet for the page content?
The <style> tag is only allowed in the <head> of HTML and XHTML, not the <body> or any of its descendants. Web browsers tend to be fairly forgiving of this in the initial parsing of a document, but when changing innerHTML I would expect that the browser would ignore any <style> elements because that type of element is not expected there.
As a workaround, would it be possible to use inline-CSS in your response, that is use the style="" attribute of the HTML elements you're passing?
EDIT: To add the CSS to the <head> would require one of two things:
Two round trips to your server:
A response that includes both and can be parsed before being inserted
In this case, I would recommend encoding your two parts into a JSON object before sending. Your callback on the AJAX action should split these and attach them to their appropriate locations (style first to avoid screen jitter)
{"style":"\ndiv#ajax7373 a {\n color:#fff;\n text-decoration:underline;\n font-weight:bold;\n \n}\ndiv#ajax7373 {\n background-color:#ff1cae;\n color:#ff6ccf;\n}","object":"\n<div id=\"#ajax7373\">\n\tThere is the contents of your div and a <a href=\"#\">link<\/a>\n<\/div>\n"}
That said, I find it hard to believe that the app favors style/content sepration so strongly and is employing a method where the style must generated by the content. Why not style the whole domain, including the expected return of your AJAX requests? Are the AJAX requested items really going to have enough variance in structure/style to warrant this?
You're stuck with either inline styles for the generated CSS or you'll have to write tons of class names for all the various styles you need so you can still separate out the styling. Then you could alter the class names via JS.

Categories

Resources