Write link to images in .js file - Symfony2 - javascript

I'm using Symfony2 and I have some links to images in my .js file - like this:
$(this).attr('src', 'img/icons/black/icon1.png');
Of course they don't work this way :( How should I set them?
At first I tried with
{{ asset('bundles/acmemy/img/icons/black/icon1.png') }}, but I soon remembered that I'm not writing in twig file.

If you are asking to link to image using JS file. You can do that by typing
IMG SRC="images/home.gif" WIDTH="100" HEIGHT="30"

if images stored in YourBundle/Resources/Public/img/
then after assets:install they will be available by this url
/bundles/yourbundle/img/*
so the answer is:
$(this).attr('src', '/bundles/yourbundle/img/icons/black/icon1.png');

you may include you assets paths in a javascript object inside your twig file:
<script>
var images = {'image1': {{ asset('bundles/acmemy/img/icons/black/icon1.png') }} };
<script>
and then in your script that has to be included after this script tag:
...
$(this).attr('src', images.image1);
...

Related

Running a JavaScript as an external script in Laravel

I have a blade code like this:
<input type='text' id="input1">
<div >
<h3 id="showData"> Data will be shown here </h3>
</div>
<script>
var input=document.getElementById('input1').value;
document.getElementById('showData').innerHTML=input;
</script>
What I want is to write the script part in a separate file (say called externalScript.js) and call it here in the blade file.
Also, I have a doubt about it. If I do that, since the script is run from an external file, how will it fetch the id values like input1 or showData ?
Write a new file called: externalScript1.js
Add the script tag, best in the head or foot part of your code.
<script src="{{ asset('externalScript1.js') }}" defer></script>
(the asset helper gets the path to the public folder, https://laravel.com/docs/8.x/helpers#method-asset)
In the end everything will load from one page, ergo the elements are found, so you won't have a problem.
Just add js file in laravel resources directory, link to webpack and compile more info.
when it comes to executing the script, attach it at the end of the page (before </body>) or wait for the page to be loaded document.addEventListener('DOMContentLoaded', function() {})
Attach the js file in the main wrapper, not in the nested blade element

Calling function in HTML, from external .js file?

I am trying to call a function I've declared in my .js file, in my HTML document.
js/newsalerts.js
function unescapeHTML(html) {
//https://stackoverflow.com/a/2989105/4650297
var div = document.createElement("DIV");
div.innerHTML = html;
return ("innerText" in div) ? div.innerText : div.textContent; // IE | FF
}
index.html (using Flask)
<html>
<head>
<script type="text/javascript" src="{{ url_for('static', filename='js/newsalerts.js') }}"></script>
<script>
queries = "{{ search_terms }}";
console.log(unescapeHTML(queries));
</script>
...
I'm trying to get the unescapeHTML function to run on my queriesvariable, but keep getting the error that
unescapeHTML is not defined
I've also tried console.log(newsalerts.unescapeHTML(queries)), same error.
Unfortunately (?) the solution to this was not a programming one. Thanks to the folks commenting on my OP, I was able to confirm that my .js file was indeed loading correctly, and the code was correct.
...except looking through the code, my unescapeHTML function was missing -- but it was in my .js file!
The problem was when I restarted the Flask server, and refreshed my browser, it must have kept the js file from the cache. Once I did a hard refresh, the full correct js file loaded and it works as expected.
So, don't forget to "hard refresh" the page if you change any of the underlying code.

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

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