I'm working in a Joomla environment but I think this is not the source of the problem.
I have a view which renders subviews (containing JavaScript code like <script type="text/javascript></script>) with AJAX. Problem is : the JavaScript code is ignored. I guess that's because it isn't in the document when it is loaded.
Here's the JavaScript code contained in one of the subview :
<script type="text/javascript">
window.addEvent('domready', function() {
$('annuler').addEvent('click', function() {
var a = new Ajax(
'{$url}',
{
method: 'get',
update: $('update')
}
).request();
});
});
</script>
Another basic example, if I load a subview with the following code in it, it won't work either :
<script type="text/javascript">
function test()
{
alert('ok');
}
</script>
<a id="annuler" onclick="test()">Annuler</a>
I'm getting the following error message : "test is not defined"
I can't find a solution to that problem so I'm starting to think that it is not a good way to use JavaScript...and, yes, I'm kind of new to event based JavaScript (with frameworks and so on).
I finally managed to put all the subviews and the JavaScript code into the same page. I'm using the CSS display property to hide/show a subview (<div>) (instead of loading it with Ajax).
Place the code you want to run in a function and call the function from an on ready block
EDIT:
Example:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Found here: http://www.learningjquery.com/2006/09/introducing-document-ready
Related
I am a web design student and fairly new to jQuery/Javascript so I know this is fairly basic, but everything I have tried has not worked. I am using unslider (unslider.com) on my main page and I am trying to pause the slider on a click event. The documentation on unslider.com shows that you can stop and start the slider based on the following code:
var slidey = $('.banner').unslider(),
data = slidey.data('unslider');
// Pause Unslider
data.stop();
The problem I am having is that I am not sure how to access or utilize these predefined methods in my own js file. Here is the code I am trying, but it is not pausing the slider:
$(document).ready(function() {
$('.button').click(function() {
var slidey = $('.banner').unslider(),
data = slidey.data('unslider');
data.stop();
});
});
Any help with this would be greatly appreciated! Thanks
After the slider is stopped, I am trying to run the following functions:
$details_link = $('.active').data('url');
$('#inner_wrap').load($details_link, function() {
$('.banner').slideToggle( "400", function() {
$('body').toggleClass('no_scroll');
$('#slider_btn').toggleClass('slider_btn_down slider_btn_up');
});
});
Here's a working fiddle.
Make sure that your JS is like so:
$(document).ready(function () {
unslider = $('.banner').unslider();
$('button.stop').on("click", unslider.data("unslider").stop);
});
Then in your HTML make sure that your button is like so:
<button class="stop">Stop the slider</button>
And you're all set.
In terms of utilizing methods from other JS files, just make sure that the location of the script tag for the library you want to use is before your own JavaScript so that the library loads before you can call one of its methods. Something like this, where application.js is your custom JavaScript:
<script src="jquery.js"></script>
<script src="unslider.js"></script>
<script src="application.js"></script>
As long as you have both javascript files linked within the same page, and the file that has the function you are calling is linked first, you will be able to call functions from other files, as described in this post:
Can we call the function written in one JavaScript in another JS file?
I've never created a jQuery plug-in before. I'm trying it out and keeping it simple for now- here's my plug-in code which is hosted on a CDN in my company:
(function ($) {
$.fn.displayToastrNotifications = function () {
alert('test');
};
})(jQuery);
I'm referencing this JavaScript file inside my page:
<script src="http://server/sites/CDN/Scripts/toastr-notifications.js"></script>
Finally, in the same page, I have:
$(document).ready(function () {
$.displayToastrNotifications();
});
Am I doing this right? The JavaScript file containing my plug-in code is being brought back to the browser per Firebug. I do not get an alert box when I refresh my page. What am I doing wrong?
EDIT
The console reports an error:
TypeError: $.displayToastrNotifications is not a function
$.displayToastrNotifications();
But, it is a function, at least I think it is...
No, that's not right. You're adding the function to $.fn, so that means it's something to be used as a method of jQuery objects:
$(something).displayToastrNotifications();
If you want a "global" function like $.ajax, then you'd set it up as just a property of $, not $.fn.
since it is a plugin it need to be invoked in a jQuery wrapper object like
$('body').displayToastrNotifications();
Demo: Fiddle
I need to learn how to initialize scripts. I have google it but dont dont really understand it.
Right now I have a toggle-script that is in a div, that entire div gets loaded in to another page. The toggle scripts work, but not when its loaded in.
$(".class").click(function () {
$(this).toggleClass("add_class");
});
If somebody have time, can you explain to me how to initialize this script?
Thanks.
You should put this script inside a document.ready call.
Eg.
$(document).ready(function() {
//Put your code here
});
If I misunderstood your question and what you actually mean is:
How do you execute the script after you load it in through an AJAX call.
Then see this question: executing script after jQuery Ajax Call
Are you calling it after the elements are loaded on the page?
You should be using on() with jQuery 1.7+
$(document).on("click", ".class", function () {
$(this).toggleClass("add_class");
});
If you want to keep your syntax, you would have to do it either after the elements are rendered, or do it on document.ready.
I figure you're using jquery.ajax to fetch the div?
If so, you should be able to add the listeners in the success-function of the jquery.ajax call:
$('#result').load('ajax/test.html', function() {
$("#result .class").click(function () {
$(this).toggleClass("add_class");
});
});
simple and best
$(function(){
//your code here...
$(".class").click(function () {
$(this).toggleClass("add_class");
});
});
I have a dilemma - my javascript code needs to be executed when the DOM is ready. However, at the same time I need to be able to hook up to the load event of another script. So hypothetically speaking I need something like this:
ExecuteOrDelayUntilScriptLoaded(getData, "sp.js");
function getData() {
(document.ready(function() {
//my code to get data from sharepoint list.
}));
}
Only the latter does not seem to work.
Please suggest!
Why not to do it like this?
$(document).ready(function() {
ExecuteOrDelayUntilScriptLoaded(function getData(){
//your code to get data from sharepoint list.
}, "sp.js");
});
Try
$(document).ready(function() {
$.getScript('sp.js', function() {
//your code to get data from sharepoint list.
});
});
For even more control over script loading, try a script loader like the simple and lightweight yepnope.js or the more complex LABjs.
If you are using jQuery, MooTools, or any other library - there is a standard function you can hook into, which checks if the DOM and your assets are loaded.
For example, in jQuery:
http://api.jquery.com/ready/
What is the best practice of activating jquery ui widgets for html loaded and inserted into the document by ajax?
I am an advocate of unobtrusive javascript and strongly believe that all functionality accessed by javascript should be also accessible without it. So in the ideal case, each form which opens in a popup, should also have its separate page and links to them should be replaced with javascript-based ajax loading.
I find this pattern very useful for loading and inserting a part of another page into the current document:
$('#placeholder').load('/some/path/ #content>*');
Or to make it more generic:
$('a.load').each(function() {
$(this).load($(this).attr('href') + ' #content>*');
});
However, I would also like to activate the javascripts from the dynamically loaded page, so that different widgets function correctly.
I know, I could add those javascripts to the current document and activate all of them in the callback of .load(), or I could use $.get() to get some JSON with html and javascripts separately, but I guess, there might be a more elegant generic solution to this.
What would you recommend?
BTW, I am using Django in the backend.
The question is how you're activating your javascript currently. If you're doing something like:
$(document).ready(function() {
$('a.foo').click(function() { ... });
})
You could consider changin things to:
$(document).ready(function() {
$('a.foo').live('click', function() { ... });
})
That way when new DOM objects are loaded the event handlers are attached.
What I've done is used the "load" option that is specifiable by jquery.ui widgets. Unfortunately, this isn't well documented, so you won't see the option here: http://jqueryui.com/demos/tabs/#options for example, but you will see it here: http://jqueryui.com/demos/tabs/#method-load
For the most part, each of the methods you invoke have an initial option that can be set, which is what prompted me to try using the load.
In my own application, I have 3 levels of nested tabs that are being created dynamically via AJAX. In order to have the javascript for each of the tabs applied dynamically, I have nested load functions that are first initiated when the document is loaded.
So my template file has:
<script type="text/javascript" src="{{ MEDIA_URL }}js/tabs.js"></script>
<script type="text/javascript">
$(function() {
$('.overall_tabs').tabs({
load: initializeOverallTabs
});
});
</script>
My tabs.js file has:
function initializeOverallTabs(event, ui){
...
$('.lvl_two_tabs').tabs({
load: initializeTabLevel2
});
...
}
function initializeTabLevel2(event, ui){
...
// So on and so forth
...
}
Also, I recommend when working inside the loaded areas to make your references be specific to that pane. This was extremely important when working with tabs. The best way I found to do this is below.
In your tabs.js file:
function initializeOverallTabs(event, ui){
$panel = $(ui.panel);
$panel.find('lvl_two_tabs').tabs(...);
}
I found this question strangely coincidental! I recently explained my solution to a few developers to the same situation with the same Jquery/Django Environment. I hope that helped!
One way I decided myself for handling widgets from external pages is parsing the HTML of the other page, searching for scripts and executing them in the current page.
For example, there is a form with autocomplete widget on another page which is loaded and inserted to this page. The autocomplete widget should be activated with specific properties, like available choices:
<script type="text/javascript">
//<![CDATA[
$(function() {
$("#colors").autocomplete({
source: ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan']
});
});
//]]>
</script>
Then in the current page I can have the following script which loads HTML and additionally collects all javascripts within it and executes them:
var oRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
$('#placeholder').load(
'/some/path/ #content>*',
function(responseText, textStatus, XMLHttpRequest) { // <-- callback function
var sScripts = "";
responseText.replace(
oRe,
function($0, $1) {
sScripts += $1;
return $0;
}
);
eval(sScripts);
}
);
One drawback here is that the current document should initially be loading all the libraries which might appear in the included forms. For example, in this case, it would be the jquery-ui including the autocomplete widget. I guess I could extend the code by searching for script tags which load external scripts and loading them in the current document if they are not present.