Running Master page scripts on imported page lines - javascript

I'm importing some php into a div block using a link like this
<a class="ajax-link" href="login.php">Login/Register</a>
and such script (that uses jquery load to fill the div block).
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});
});
Now let's say the loaded php file after running the php portion also contains a link with "ajax-link" class and I want that link too to change the contents of that div block
<?php
...
?>
<a class="ajax-link" href="view.php">View content</a>
But rather than running the above mentioned function on it, it seems to ignore it completely and opens a new page instead.
So basically... how can I run that script on imported parts of the page?

This is where event delegation comes in handy.
$(document.body).on("click", "a.ajax-link", function(e) {
// ...
});

This code needs to be re-run ... dynamically added objects are not included in previous on clicks.
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});
... you could also ... turn off the old watcher.
$("a.ajax-link").off("click");
UPDATE:
Try ...
$("a.ajax-link")
.off("click")
.on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});

You have to apply the click listener on the newly added link as well, as the element has to be loaded into the DOM when applying the click listener in order for it to be applied. However, if you just re-run the same code you'll like run into the problem of having two event listeners on the first ajax-link.
Try this:
// We still use on doc ready to be sure the
// first link is present before applying listener
$(function()
{
// Reset all listeners on ajax-links and
// then apply listeners via function
resetAjaxLinks();
});
// This function will remove any ajaxlink
// listeners and then apply them correctly
function resetAjaxLinks()
{
// Remove event listeners and then on click....
$("a.ajax-link").off('click').on("click", function(e)
{
// Prevent default link action...
e.preventDefault();
// Load in your content...
$("#body-element").load(this.href);
// Once content is loaded in, reset event listeners!
resetAjaxLinks();
});
}
EDIT: This is not the best method for this. Instead, use event delegation as specified by this answer.

Related

Issues with jquery delegate

I'd like know how to fire unique Handler triggered by clicked element loaded dynamically in parent div (so delegate) or when is directly loaded.
Firstly, <a class="manage-lnk>Manage</a> Elements are loaded directly, but after, further there are loaded dynamically
html
<div id="viewContainer">
<a class="manage-lnk">Manage</a>
</div>
lib.js.
I have to find this tip for it to work in both cases
$(document).on('click','.manage-lnk',function(){
alert(1);
});
$('.manage-lnk').on('click',function(){
alert(1);
});
what i want is to fire alert(1) although the element is dynamically loaded or not.
(PS:Excuse me for my english i speak french)
Fire this:
$('.manage-lnk').on('click',function(){
alert(1);
});
Each time you dynamically add another one of these:
<div id="viewContainer">
<a class="manage-lnk">Manage</a>
</div>
If it's dynamically loaded after the JS has fired it will not have the event attached.
It would make sense to add it to a function you can call just after the code that dynamically adds in the HTML:
function addNewHtmlSectionFunctionName() {
//Code to add div dynamically
}
function attachClickEventToManageLnk() {
$('.manage-lnk').on('click',function(){
alert(1);
});
}
$(function() {
addNewHtmlSectionFunctionName();
attachClickEventToManageLnk();
});

jQuery Turnbox.JS - Animate without user interaction

I really like to use KeiichiroHirai's Turnbox.JS script (http://www.noht.co.jp/turnbox),
However, This script seems only to work with a user clicking/hovering on any button this script is appending itself to.
I wish use these animations when DOM is ready,
I tried:
$(function() {
$.turnBoxLink({
box: ".example"
});
});
But since I'm posting here, It's obviously not working.
Thank you in advance!
If you wish to do that when DOM is ready you should wrap your init code into
$(document).ready(function() {
// go when DOM is ready
});
or
$(window).load(function() {
// go when page and images are loaded
});
And also, Turnbox can be initialized like this :
HTML markup
<div class='login_form'>
<h3>My form element<h3>
</div>
With the following code you'll get the extra simple sample, without any options. but for test purposes it could be good to start here :
$(".login_form").turnBox();
If now, you want to launch the animation at specific event (for example to the ready or load event), you'll be able to do so by using :
$(".login_form").turnBoxLink({
box: ,
events: "ready", // you can also try 'load'
dist: "next"
});
After initializing, click the generated .turnBoxButton child element:
$.turnBoxLink({
box: ".example"
});
setInterval(function() {
$(".example .turnBoxButton").click();
}, 1000);
This will spin the box every second.
If You want to programmatically trigger a click event on an element with jQuery You can use the .click() function.
$(document).ready(function() {
$('.sample').turnBox();
...
$('.sample').click();
});

jQuery attach click handler with on() inside anonymous function definition

I try to attach a click handler for links with a specific class within an anonymous function definition which is unfortunately not working. Why?
(function($) {
var init = function() {
console.log('init...');
mediaPlayer($('.media-toggle'));
};
var mediaPlayer = function(mediaLink) {
console.log('media player init ...');
console.log(mediaLink);
mediaLink.on("click", function(e) {
console.log('media toggle clicked ...');
e.stopPropagation();
e.preventDefault();
alert('clicked');
});
};
init();
})(jQuery);
The used HTML markup looks like:
<ul>
<li>
Preview 1
<audio src="https://www.foo.org/audios/preview1.mp3"></audio>
</li>
<li>
Preview 2
<audio src="https://www.foo.org/audios/preview2.mp3"></audio>
</li>
<li>
Preview 3
<audio src="https://www.foo.org/audios/preview3.mp3"></audio>
</li>
</ul>
I have to admit, that I use the MediaElement.js library to play the audio files, which works fine.
If I would use a "global" function handler definition like the code snippet below, it would work. But I don't understand why and what is the difference.
$(function(){
$('.media-toggle').click(function(e) {
e.preventDefault();
alert('Clicked ...');
});
I missed a very important part on my example. A piece of JS code after this function is or was responsible for the not working code. Which removed all the event handlers by moving a parent div element (with all the links inside) to another part within the DOM tree.
Instead of
$(".preview-audio").remove().insertAfter($(".foo"));
I should rather have written
$(".preview-audio").insertAfter($(".foo"));
The notable difference between the two pieces of code is that the one which doesn't work runs immediately and the one that does runs on DOM Ready.
The problem is almost certainly that you are calling $('.media-toggle') before any elements with that class exist in the DOM, so it has a length of 0.
Replace your IIFE:
(function($) {
...
})(jQuery);
with a ready handler:
jQuery((function($) {
...
});
You have defined a function mediaPlayer but you have a typo when calling it: medialPlayer($('.media-toggle'));
It's likely you would see an error in the console.
Also, make sure you've got this inside an onload or $(document).on('ready') function to ensure that the DOM node you're interested in (.media-toggle) has been loaded.
You are missing the doc ready code in here:
init();// possibly element is not rendered.
})(jQuery);
Instead try this:
$(init);
})(jQuery);
Or:
(function($,document) {
....
$(document).ready(init);
})(jQuery,document);

Loading several .php file into one div

Hello i have this code to load php file into div. Its working but i need load next file into this div.
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href).fadeToggle(1000);
});
});
</script>
<li><a class="load" href="zzz.php">zzz</a></li>
If i click "zzz" link loading file into my div (file table with images) i need hide this page and load next by click image.
UPDATE
Now working
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().empty().load(this.href).fadeToggle(1000);
});
});
</script>
You just simply need to bind another click event to an image (or table body) that you load through load() function. However, you may experience some issue with your click not working, and heres why:
If you attach two click handlers, one for a.load and second for, let's say, .image than only the first event will actually get bind to its element, and the socond one won't be attached because, well, .image doesn't exist yet - not untill you load it.
You could expect, that once you php file content will get loaded (with .image elements in it), then clicking them will fire an action you have declared, but it won't - those .image's are new DOM elements and they missed an event binding procedure which was done only once when the DOM was created (or DOM was ready if you use $.(document).ready()).
So, in order to get those clicks to work you need to either attatch them on load() function callback, like so:
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href, function(){
$(".image").on("click", function(e) {
$("#zaw").hide().load(/* load what you want */);
});
})
.fadeToggle(1000);
});
or insert .image click event binding inside php file you are loading or use some sort of delegation, for example:
$(document).on('click', '.image', function(){
/* do what you want */
});
which will make sure that even new, dynamically created DOM element will fire an action you want.

Container hierarchy access for jQuery elements

JQM elements on physical page:
#page_test1
button changing page to #page_test2
#page_test2
div #place to put something programmatically
to put button inside #place container I wrote the following (working) code:
$(document).on('pagebeforeshow', '#page_test2', function(event) {
$('#place').empty();
$('#place').append('Dynamic button inserted by JavaScript');
$('#place').trigger('create');
});
Ok, but when I take an attempt to move .on body to script level (directly under script tag) code inside become wrong because of context loose:
$(document).on('pagebeforeshow', '#page_test2', function(event) {
addButton(); // Attempt to move widget manipulation up
});
// Widget manipulation not changed but moved outside (level up) .on
// Not working
function addButton() {
$('#place').empty();
$('#place').append('Dynamic button inserted by JavaScript');
$('#place').trigger('create');
}
How to access JQM elements from different levels of JQM hierarchy and outside of it?
Guess it is very basic for JQM / Ajax so I will very thankful to take URL with common information.
To access an dynamically through code outside the target page, use the the following:
$(document).on(event, '.selector', function() { });
To access an dynamically through code inside the target page, use the the following:
$('.selector').on(event, function() { });

Categories

Resources