Django - Javascript does no access DOM? - javascript

I am trying to implement this code to my Django application.
I manage to get the code on the page using code blocks in my index.html.
It seems like the styles from the css is displaying correctly. I also manage to play songs, but the pause button, different cover images and song titles does not change when they are clicked/changed.
For me it seems like the JavaScript is not able to change the style of html elements in the DOM.
I know that JS files is not processed by Django's template engine. So I am using this code, so I can reference this global variable from within the js-file.
<script>
var MEDIA_URL = "{{MEDIA_URL}}";
</script>
<script type="text/javascript" src="{{MEDIA_URL}}/js/myscript.js" ></script>
inside the JS file there is two places where the variable is referred,
$('.player .cover').css('background-image','url(MEDIA_URL + audio/' + cover+')');;
song = new Audio(MEDIA_URL+'audio/' + url);
This reference do actually take place, but for the rest of the JS-file.. none of the addClass, removeClass etc. do affect the DOM.
When trying this code outside the Django framework, everything works as expected.I am pretty sure that there is something I am ignoring, that is causing this problem.. but I cannot seem to figure out what it is!
Please help!

That code shouldn't work. You've mixed up some quotes:
$('.player .cover').css('background-image','url(' + MEDIA_URL + 'audio/' + cover + ')');
Definitely watch your syntax. Another thing you could have done to test things out is actually put the MEDIA_URL value in the jQuery function, before trying to substitute in the variable.

Related

Accessing variable within document.ready

I know this has been asked before but mine might be a little different.
I have an HTML page that I have little control of and has a restriction on what JavaScript can be used. In this HTML I decalare a variable, in this case an array of image URLs.
In an external file I am trying to use this variable. The variable works anywhere within this file, but as soon as I try and show it within document.ready it becomes undefined.
Making it awkward is that I can't call the external script without writing it in a document.write script (it's within eBay and you can't call external scripts easily)
Can anyone help with why it doesn't work, or a better way of doing it?
I have full control of the JavaScript file, but the HTML I have access to, but limited to what I can write in there without eBay blocking it. It's for this reason the document.write has to be used.
My code is like this (a stripped out version):
console.log("Images: " + prodImgs);
$(document).ready(function() {
console.log("Images inside doc ready: " + prodImgs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<head>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var prodImgs = new Array();
prodImgs[0] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[1] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[2] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[3] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs = prodImgs.filter(function(v) {
return v !== ''
});
document.write("<" + "script src='http://example.com/Scripts/jquery-1.8.1.min.js' type='text/javascript' " + "></" + "script><" + "script src='http://example.com/Scripts/myscripts.js' type='text/javascript' " + "></" + "script>");
</script>
</head>
<body>
If you view the source on eBay, they already reference jquery version 1.7, on the home page anyway.
http://ir.ebaystatic.com/rs/v/jmalt0eyvq1k1k2ezqntv51k5mo.js
Suggest there is possibly a conflict. I would strongly suggest not using jquery unless you must because you will be at the whim of whatever eBay decide to do with their general code base.
Using an iframe to embed the content or features would allow you to have independent code that won't clash with ebay's core, although you will potentially have cross-site scripting errors depending on what you are trying to achieve.
Perhaps a combination of both. I assume you are trying to embed a slide show. Have a iframe hosted elsewhere for that, and then keep to general content and pure javascript if you need.
Remember to use closures and limit globals as again you may conflict with ebays base code.
did you mean you want to declare a variable in your html page.
and want to access that variable in .js file?? if so then in html file when you declare a variable dont use the var keyword.
dont use this
var prodImgs=new Array();
use the below one
prodImgs=new Array(); -- use this.
now you can access the prodImgs variable in .js file

how to re-factor/extract methods to separate file for re-use

I'm fairly new to the whole JQuery/javascript world, but I've managed to wack together a working jqgrid with a datepicker & custom control (used jquery auto complete) based on code samples i found on the net. I've added the code to a T4 template in my project as it'll probably act as a base/starting point for most pages. (Side note. I'm using asp.net MVC)
JFIDDLE: LINK
1.) I'd like to move the initDateEdit & initDateSearch to the same function (using a parameter, to disable/enable the showOn property) as they are basically similar.
2.) How would be the best way to set nonWorkingDates from outside the new function/file. same applies to the autocomplete_element (I'd like to specify the url)
Changing
"function nonWorkingDates(date)" to => "function nonWorkingDates(date, nonWorkingDates)"
isn't working, (guess it's got got something to do with how its gets called "beforeShowDay: nonWorkingDates")
Thanks in advance!
If you have a chunk of JS code like this:
<script type="text/javascript">
... code goes here ...
</script>
You simply copy the whole thing, eliminate the containing script tags, and save the raw code
... code goes here ...
to a file, which you then include with:
<script type="text/javascript" src="yourfile.js"></script>
However, since you're using jquery, you'll have to make sure that this above snippet is placed AFTER the script tag that loads up jquery, or you'll get a "no such function" syntax error.

how can I detect page when I compile all javascript to one file

I compile all my javascript for different pages into one file, so I have to identify page for my all.js. I can put a hidden element in my pages and let javascript detect this element, but I don't like this solution, are there any other ways to do this?
You could go by the url using location.href (or another field from the location object).
However, a better approach is using a data- attribute on the body tag, e.g. <body data-page="whatever"> and then using $('body').data('page') to retrieve the value.
If you script is based on pages, then compiling them into one script is a bad idea, load the file separately, it will be lighter and definately increase some performace.
I am not sure, why do you need this, but in general it is not good practice to change dynamicaly change content of javascript file, since you are disabling javascript cacheing, what can be performance issue later.
Any way, you can solve it from other side, what about using all.js just to detect the page, where are you and then you can use this information, to load right javascript file dynamicaly, like in the following example
document.write('<script src="'+location.pathname+'.js"></script>');
Which will load same file as you are on, just with .js extension. So for example on index.html page it will load index.html.js file
I almost always use MVC frameworks and tend to put my action and controller as classes on the body element
<body class="main_controller index">
Which lets you do things like this:
$(document).ready(function(){
//Only for lessons#search
if (!$(body).hasClass('lessons search')) {
return;
}
function close_style_filter_box() {
$('#style_filter_box').slideUp();
}
});
$(document).ready(function(){
//Only for main_controller#index
if (!$(body).hasClass('main_controller index')) {
return;
}
function do_something_else_on_this_age() {
....
}
});
Another way is using javascript variable:
var PAGE = 'page1';

How do I get Aptana/Firefox to execute my JavaScript rather than show the code?

I'm extremely new to coding and I'm reading a book on it. And I think I have the basics down on this little test project I'm doing, but whenever I test the page I just see the code I used. Here's the entirety of my code.
<script type = "text/javascript">;
//<![CDATA[
// from concat.html
var person = "" ;
person = prompt( "What is your name?") ;
alert("Hi there, ") + person + "!");
//]]>
</script>
Honestly I don't know what the CDATA is for or what concat.html is.
How can I get Firefox to run my JavaScript rather than just show the code?
Try wrapping it in <html> to make the whole page get treated as HTML. Does the file have a .js extention, by any chance?
CDATA is to distinguish code from markup.
Put it in an HTML file.
So, first, save it as scriptname.html - you're embedding JavaScript within an HTML file.
Next, make it valid html - add <html> to the top and </html> to the bottom. And <head> and <body> tags where appropriate - if you don't know what those are, head over to any HTML site to look them up (www.diveintohtml5.org is nice, if you can follow it.)
Better install Firebug plugin for Firefox or use other browser's Javascript console. It will allow you to run your code
http://www.w3resource.com/web-development-tools/execute-JavaScript-on-the-fly-with-Firebug.php

Dynamic javascript reference

I've inherited some code (not mine- I swear!) which uses a session variable in the header of the HTML to determine which javascript file to link to.
i.e.
<SCRIPT language="javascript" src="../JavaScript/<%=Session("jsFileName")%>.js"></SCRIPT>
It does work, except that it won't let me change to design view. It gives the message
"Could not open in design view. Quote Values differently inside a '<%... "value" ...%>' block."
Anyone got any suggestions as to a workaround, that doesn't involve a huge rewrite.
Try this:
<SCRIPT language="javascript" src='../JavaScript/<%=Session("jsFileName")%>.js'></SCRIPT>
Notice use of ' instead of " for src attribute.
Can't you just comment out the SCRIPT tag in code view and then swith to design view?
Or replace the outer double quotes with single so you have:
src='../JavaScript/<%=Session("jsFileName")%>.js'

Categories