how to structure javascript files? - javascript

I have
base.html
pageA.html
pageB.html
pageA.js
pageB.js
pageA.js has code for pageA.html, pageB.js has code for pageB.html.
both pageA.js and pageB.js uses jQuery.
currently I am including all of the scripts in base.html, like so:
<html>
<body>
<div id="contents">
<!-- pageA.html / pageB.html comes here -->
</div>
<script src="js/jquery.js"></script>
<script src="js/pageA.js"></script>
<script src="js/pageB.js"></script>
</body>
</html>
I'd like to load pageA.js only for pageA.html and pageB.js for pageB.html, as the code in each file is not needed in the other page.
I've looked into requires.js library, but I'm not sure yet if it is the right solution for my problem. What are the best practices for structuring javascript files in this type of situation?

I think that the best you can do is add the <script src="js/pageX.js"></script> in the end of the pageX.html IF this page is loaded dynamically.
If the page isn't loaded dynamically, it may load before jquery.js and break you javascript.
Or you can read the current URL and load the correct script based on this info, like this:
var scriptPath;
var currentPage = window.location.pathname;
if (currentPage == "pageA.html")
{
scriptPath = "pageA.js";
}
else if (currentPage == "pageB.html")
{
scriptPath = "pageB.js";
}
var scriptElement = document.createElement("script");
scriptElement.setAttribute("type", "text/javascript");
scriptElement.setAttribute("src", scriptPath);
document.getElementsByTagName("head")[0].appendChild(scriptElement);

Do you have JavaScript to load in the contents of each html file? If so, and you have JavaScript code to run once each file is loaded you can call the required setup functions inside the load function like this:
base.html
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/pageA.js"></script>
<script type="text/javascript" src="js/pageB.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#loadPageA').on('click', function()
{
$('#contents').load('pageA.html', function()
{
setupPageA(); // defined in pageA.js
});
});
$('#loadPageB').on('click', function()
{
$('#contents').load('pageB.html', function()
{
setupPageB(); // defined in pageB.js
});
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA">Load Page A</a>
<a id="loadPageB">Load Page B</a>
</body>
<html>
Or, you if you just want to run pageA.js when pageA.html is loaded in you can just include the pageA.js script element in page pageA.html itself, like this:
pageA.html:
<div id="pageAContent">Page A</div>
<script type="text/javascript src="js/pageA.js"></script>
pageB.html:
<div id="pageBContent">Page B</div>
<script type="text/javascript src="js/pageB.js"></script>
base.html:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#loadPageA').on('click', function()
{
$('#contents').load('pageA.html');
});
$('#loadPageB').on('click', function()
{
$('#contents').load('pageB.html');
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA">Load Page A</a>
<a id="loadPageB">Load Page B</a>
</body>
<html>
The dynamic script src solution:
base.html:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function loadScript(script)
{
// Modify the existing script tag
if($('#dynamicScriptTag').length != 0)
{
$('#dynamicScriptTag').attr('src', script);
}
else // Create script tag
{
$('<script>').attr('type', 'text/javascript')
.attr('src', script)
.attr('id', 'dynamicScriptTag')
.appendTo('head');
}
}
$(document).ready(function()
{
$('#loadPageA').on('click', function(event)
{
event.preventDefault();
$('#contents').load('pageA.html', function()
{
loadScript('js/scriptA.js');
testScriptB(); // test if we can still call a function in scriptB.js
});
});
$('#loadPageB').on('click', function(event)
{
event.preventDefault();
$('#contents').load('pageB.html', function()
{
loadScript('js/scriptB.js')
testScriptA(); // test if we can still call a function in scriptA.js
});
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA" href="#">Load Page A</a>
<a id="loadPageB" href="#">Load Page B</a>
</body>
</html>
pageA.html:
<div id="pageAContents">Page A</div>
pageB.html:
<div id="pageBContents">Page B</div>
js/scriptA.js:
console.log($('#pageAContents').text());
function testScriptA(){ console.log('Can still call testScriptA!'); }
js/scriptB.js:
console.log($('#pageBContents').text());
function testScriptB(){ console.log('Can still call testScriptB!'); }

I ended up using Jinja(a template engine) to place the javascript files like following:
base.html
<html>
<body>
<div id="contents">
{% block contents %}
{% endblock %}
</div>
<script src="js/jquery.js"></script>
{% block scripts %}
{% endblock %}
</body>
</html>
pageA.html
{% block contents %}
..page A contents..
{% endblock %}
{% block scripts %}
<script src="js/pageA.js"></script>
{% endblock %}
If you are using a template engine, it could be a viable solution.

Related

Panzoom on django with jquery

I have a really basic django app that displays .png images using django ImageField and ask the user to vote on different choices.
Now I need to make it interactive so that the user can also zoom and pan the images in the form.
I've downoad this github https://github.com/timmywil/jquery.panzoom and followed the instructions in my detail view: detail.html :
<div id="img">
<img src="{{question.image.url}}"/>
</div>
{% load static %}
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("img").panzoom();
$("img").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
But nothing happens at all, the image is displayed in a fixed manner.
Previously I had some issues with 404 errors and now It seems to properly load the .js but It still doesn't work.
Thank you in advance for your help.
You have to have:
1) <script type="text/javascript" src="_path_to_your_JS_panzoom_file"></script> - to import that file
2)
<script type="text/javascript">
jQuery(document).ready(function(){
$(".panzoom-elements").panzoom();
// Pass options
$("a.panzoom-elements").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
OR 2-b) Add those your code to a separate .js file and import it at the same way as in paragraph 1.
OK, finally I found the problem. The documentation is probably done for people who have a bit more background in that field! But of course other imports are required to make it work:
{% load static %}
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.mousewheel.js' %}"></script>
<section>
<div class="parent">
<div class="panzoom">
<img src="{{question.image.url}}">
</div>
</div>
<div class="buttons">
<button class="zoom-in">Zoom In</button>
<button class="zoom-out">Zoom Out</button>
<input type="range" class="zoom-range">
<button class="reset">Reset</button>
</div>
<script>
(function() {
var $section = $('section').first();
$section.find('.panzoom').panzoom({
$zoomIn: $section.find(".zoom-in"),
$zoomOut: $section.find(".zoom-out"),
$zoomRange: $section.find(".zoom-range"),
$reset: $section.find(".reset")
});
})();
</script>
</section>

How to access to a javascript variable inside another html.twig file in symfony2?

I would like to know how to access to a javascript variable inside another html.twig file in symfony2. Let's assume that we have two html\twig files: file1.html.twig and file2.html.twig, their codes are as below:
The code of file1.html.twig:
<html>
<head>
<script>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
</script>
</head>
<body>
</body>
</html>
The code of file2.html.twig:
<html>
<head>
<script>
function f1(){
//here is the code that I need to access to the variable calendar of the file file1.html.twig
}
</script>
</head>
<body>
<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:idg})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
//here the body of the form
</form>
</body>
</html>
Actually, what I would like to know is how to access to the variable "calendar" of file1.html.twig inside the file file2.html.twig. So my question is it possible to do that??..If yes, how?
Put the code you want to share in a .js file:
// src/Acme/FooBundle/Resources/public/js/sharedCode.js
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
Then just include the script everywhere you want:
<html>
<head>
...
</head>
<body>
...
{% javascripts '#AcmeFooBundle/Resources/public/js/sharedCode.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
</body>
</html>

Dictionary passed to js not working

I am new to javascript. I am working on django project. I need to pass the dictionary template variable to javascript and I have not been able.
views.py includes:
def index(request):
name={'bishal':509,'bishnu':510}
return render_to_response("test.html",Context({'name':simplejson.dumps(name)}))
test.html includes:
{% load staticfiles %}
{% block include_js %}
<script src="{% static "js/chart.js" %}"></script>
<script src="{% static "js/test.js" %}"> </script>
{% endblock include_js %}
{% block main_content %}
<script type="text/javascript" src="static/js/test.js"></script>
<script type="text/javascript">
var name={{name}};
</script>
<button class="btn btn-primary" id="btn1" type="button" onclick="myfunction()">1st visualization</button>
{% endblock %}
test.js includes:
$(function myfunction() {
document.getElementById('btn1').onclick=function(){
name=JSON.parse(name);
alert(name);
};
});
But error occurs saying:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
I tried similar thing in html as:
<html>
<head>
<script type="text/javascript">
function myfunction()
{
dict=JSON.parse(dict);
alert(dict);
}
</script>
</head>
<body>
<script type="text/javascript">
var dict='{"bishnu": 509, "bishal": 510}';
</script>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
<p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
which worked perfectly. Please help!
Ignore all the JavaScript. The key line in your problem is:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
404 is the HTTP code for 'file not found', which means that you're using the incorrect path to reference your JavaScript file. Fix that, and you may find that your solution then works - or, if not, at least breaks differently.
#Adrian is right about the error message, but I suspect that the problem you're thinking of is caused by not putting quotes around {{name}} in test.html. Try:
<script type="text/javascript">
var name='{{name}}';
</script>

Where do you put the relative url in a jQuery code?

I have to reference my two html documents in divs to a primary html and I can't get my other htmls to render.
This is my script in the head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
These are the divs in the body:
<div id="left"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#left').load("left.html");
});
</script>
<div id="right"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#right').load("right.html");
});
</script>
Move your script to the header:
<script type="text/javascript">
$(document).ready(function(){
$('#left').load("left.html");
$('#right').load("right.html");
});
</script>
Then ensure that your relative URIs are correct. Are both left.html and right.html in the same folder on the server as the page that requires them?

Jquery Replace content in runtime issue

What I am trying to accomplish is, using jQuery, dynamically replace the content (generated from another javascript) of div tag with id="Test".
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(function(){
$("#Test").html('<b>test content</b>');
});
</script>
</head>
<body id="testAgain">
begin
<div class="scrollable">
<div class="items" id="Test">
</div>
</div>
end
</body>
</html>
As you can see,
$("#Test").html('<b>test content</b>');
replaces the html code of div tag with id="Test" with html code
<b>test content</b>
this works perfectly fine. I am getting rendered html as
begin
test content
end
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
function TestScript(){
document.write('<b>test content</b>');
};
</script>
<script type="text/javascript">
$(function(){
$("#Test").html(TestScript());
});
</script>
</head>
<body id="testAgain">
begin
<div class="scrollable">
<div class="items" id="Test">
</div>
</div>
end
</body>
</html>
Here,
$("#Test").html(TestScript());
replaces the html code of div tag with id="Test" with generated html from javascript
TestScript()
I am getting rendered html as
test content
It replaces the entire content of the html file. How to resolve this problem?
Kindly help.
Thanks,
John
Try this:
<script type="text/javascript">
function TestScript(){
return '<b>test content</b>';
};
</script>

Categories

Resources