I'm trying to load content without reloading the whole page with this code
$(document).ready(function() {
$('article').load('content/index.php');
$('a.cta , a').click(function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
For the most part its working fine as seen here:
The only problem I'm getting is that the links withing my content area aren't working but every other link outside my content area is. Why is that? What am I missing in my code?
that is beacuse you need to delegate the dynamically added element with on. click events won't work for dynamically added elements..
try this
$(document).on('click','a.cta , a',function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
delegating it to the closest static parent is recommended for better performance.
$(article).on('click','a.cta , a',function() {
link to read more about on delegated event
It's because those as within the article element are dynamic. The click event was never bound to those. Instead, use event delegation:
$('article').on('click', 'a.cta, a', function(e) {
e.preventDefault(); //better than return false
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
});
You have to use delegated events (on() function).
$('article').load('content/index.php', function () {
$("article").on("click", 'a.cta , a', function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
See the documentation for more information.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
I managed to get it to work with this :
$(document).ready(function() {
$('article').load('content/index.php', function () {
$(document).on('click','a.cta , a',function() {
var page = $(this).attr('href');
$('article').load('content/' + page + '.php');
return false;
});
});
});
It's really frustrating when you barely know what you are doing.
try commenting out the line return false; and all the links will work.
so...
return false;
change to...
//return false;
Related
My algorithm:
I get the DIV text from php/SQL ($.get( "read.php"...)
APPEND contenteditable div with loaded text by jQuery
check the div value, if there is errors in text I make div red (assign class, $(this).addClass("fill_red");)
on every change of text - check and assign/remove class if needed.
Problem is: with preloaded text - everything is working.
But when I append div using JS - check function don't works.
I searched the web, maybe on() method helps me.
But what event?
It should be something like onload, onchange..?
(yes, I could make div generated by php and solve the problem, but I dont want full refresh)
Thank you!
part of code:
//texts load
$(function() {
$.get( "read.php", function( data ) {
var ionka = data.split(' ');
ionka.forEach(function(item, i, arr) {
var app_text = "<div id=\"segm" + i + "\" contenteditable role=\"textbox\">" + item + "</div>";
$("#textarea").append(app_text);
});
});
//checks
var intRegex = new RegExp('^[0-9/\]{5}$');
$('#textarea div').each(function(i,elem) {
if(!intRegex.test($(this).text())) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
});
// edit on change. Blur because of contenteditable
var segm_array = [];
$('#textarea div').each(function(i,elem) {
$(this).blur(function() {
if (segm_array[i]!=$(this).text()){
segm_array[i] = $(this).text();
if(!intRegex.test(segm_array[i])) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
}
});
});
You dont show much code here, but my guess is that you are trying to add class before new data is loaded into dom
$.get( "read.php" ).done(function( data ) {
// addClass etc
});
I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.
I've created a php template with variables library and what not all pulled into an index page I've created a basic script with fades the page in and out on load and have got that working the next thing I wanted to do is to use my navbar links to pull formatted content into the page (as I'm using foundation 4 framework) now the code I tried is as follows
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
the idea is that onclick it removes the content with the wrapper displays a loading gif and then loads the page content which is stored in the link referred to in the
but its not working is just reloading the whole page . . . . i have tried reading up and it says that you can use
You can extract from another page using the load method thus >$('#targetElement').load('page.htm #container') syntax.
and using the get function but im not to good at all this jquery is there a way I can do it in php or where am I going wrong with what I've done.
Try this....You were calling the load, and functions inside improperly...
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
//window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,showNewContent);
}
function showNewContent() {
$('#content').show('normal',hideLoader);
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
When a user clicks a link the browser by default unloads the current page and loads the page indicated by that link.
You need to prevent the default behavior of the browser, in order to do this you need to call the .preventDefault() method on the click event that was triggered for that link.
$('#your-context').click(function(event) {
event.preventDefault();
/**
* the rest of your code here
*/
});
I'm working with php, jquery and fullcalendar ( http://arshaw.com/fullcalendar/ )
I've setted a function on click event
$('#calendar').fullCalendar({
eventClick: function(event) {
myFunct(event);
}
);
Now, when I load this page, I have 2 cases:
- 1) with NULL $_GET[idEvent] and this simply work
- 2) with $_GET[idEvent] In this case, I want that automatically start the callback associated on click event of my fullcalendar
I decided to slightly modify fullcalendar source and add a "id" attr on each rendered event, and then write this code:
if(isset($_GET['id'])){
$id = $_GET['id'];
echo '<script type="text/javascript">
$("#idEvt'.$id.'").click();
</script>';
}
I do not think theoretically that the code is wrong..but it not work...probably because the loading of the calendar takes a long time to load and my ** $("#idEvt'.$id.'")** is not found.
Can anyone help me or has already used fullcalendar?
EDIT:
Thank you! This is the solution:
I've add a jquery function to bring get variables from url
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
Then in fullcalendar initialization
$('#calendar').fullCalendar({
eventClick: function(event) {
myFunct(event);
},
eventAfterRender: function(event, element, view ) {
var idEvt = $.getUrlVar('id');
if(event.id==idEvt){
myFunct(event);
}
}
In this way is not necessary modify fullcalendar source code or use php.
Thank you for suggestion!!!
I think you are looking for eventAfterRender callback. This will be called immediately after event is placed at its final position on the calendar. You can check for certain values and then decide whether or not to call a function. Click Here to see the parameters accepted by this callback.
I am working with AJAX with prototype and PHP. It is working for me but I need some small changes. Following is my running code for AJAX request:
JS/Prototype:
function ajaxRequest(url) {
new Ajax.Request( url, {
method: 'get',
onSuccess: function( transport ) {
// get json response
var json = transport.responseText.evalJSON( true );
alert(json);
},
onFailure: function() {
alert('Error with AJAX request.');
}
});
return false;
}
HTML:
<a href='javascript:ajaxRequest("/testajax/ajaxresponse");'>Testing AJAX</a>
Question:
Now I want to change my link like this:
<a href='/testajax/ajaxresponse' class='AjaxLink'>Testing AJAX</a>
So prototype function should capture click event of class='AjaxLink' links and then get href part of clicked link and proceed. How can I change my above prototype function for such kind of links.
Thanks
If you have Prototype 1.7 then this way is available:
document.on('click', 'a.AjaxLink', ajaxRequest.curry('/testajax/ajaxresponse'));
Otherwise you'll have to rely on good old Event.observe:
$$('a.AjaxLink').invoke('observe', 'click',
ajaxRequest.curry('/testajax/ajaxresponse'));
Just re-read the question and I see you want to use the href attribute. Jan Pfiefer was very close.
document.on('click', 'a.AjaxLink', function(event, element) {
return ajaxRequest(element.href);
});
This wont work. Why do you want such a link? If a link is specified in this way any click on it will follow its href and change location of actual document. Only way to prevent such a behavior then is by adding onclick again or in $(document).ready bind onclick handler, and manualy cancel the event.
UPDATE
However to bind onclick event on all links with AjaxLink class,execute request and cancel the event:
$(document).ready(function(){
$('.AjaxLink').click(
function(e){
ajaxRequest(this.href);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
);
});
This will work:
$$('a.AjaxLink').each(function(element) {
element.observe('click', function(e) {
var element = e.element()
Event.stop(e)
alert(element.href)
});
})