jquery fullcalendar click callback after loading - php

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.

Related

Jquery accordian within php, but call dynamic php script onclick

Here is the code I have currently,
<div class="panel">
<?php
if(isset($Uniid)) {
if (isset($from)) {
$url='Inevent.php';
include("display$category.php");
}
}
?>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');
for (var i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var setClasses = !this.classList.contains('active');
setClass(acc, 'active', 'remove');
setClass(panel, 'show', 'remove');
if (setClasses) {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
});
</script>
The main class which is the accordian is displayed currently, but when I click on the accordian, is when I want the panel to be executed, how do I go about doing it.
You can out your php code in a separate file and then call it with AJAX.
If you name your php file "loadPanel.php" then the AJAX request would look like this:
$.ajax({
url: "loadPanel.php"
}).done(function(response) {
$( '.panel' ).html( response );
});
Then add whatever php code you want inside you panel div to the loadPanel.php file.
The documentation for ajax is on the jQuery site here: http://api.jquery.com/jquery.ajax/.
There is a solution that isn't well known, but very powerful that consist in updating a part of the page with jQuery (works with the latest version of jQuery). So, to do that, you don't even have to create another page, so you just have to use the jQuery load() function.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that you can use this method like this:
$( ".panel" ).load( window.location.href );

Jquery selector not working after append

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.

jQuery : AJAX Load Content No Page Refresh

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;

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

JQuery, AJAX, PHP, XML; Image overlay script stops working on callback content

A button click fires my function that fetches image data via an AJAX-call:
$("#toggle_album").click(function () {
album_id = $("#album_id").val();
$.post('backend/load_album_thumbnails.php', {
id: album_id
}, function(xml) {
var status = $(xml).find("status").text();
var timestamp = $(xml).find("time").text();
$("#album_thumbs_data_"+album_id+"").empty();
if (status == 1) {
var temp = '';
var output = '';
$(xml).find("image").each(function(){
var url = $(this).find("url").text();
temp = "<DIV ID=\"thumbnail_image\">[img-tag with class="faded" goes here]</DIV>";
output += temp;
});
$("#album_thumbs_data_"+album_id+"").append(output);
} else {
var reason = $(xml).find("reason").text();
var output = "<DIV CLASS=\"bread\">"+reason+"</DIV>";
$("#album_thumbs_data_"+album_id+"").append(output);
}
$("#album_thumbs_"+album_id+"").toggle();
});
});
The data is returned in XML format, and it parses well, appending the data to an empty container and showing it;
My problem is that my image overlay script:
$("img.faded").hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
});
... stops working on the image data that I fetch via the AJAX-call. It works well on all other images already loaded by "normal" means. Does the script need to be adjusted in some way to work on data added later?
I hope my question is clear enough.
Okay, apparantly I hadn't googled it enough. Surfing my own question here on stackoverflow pointed me to other questions, which pointed me to the JQuery live() function: live().
However, it does not work on hover(), so I rewrote the script to use mouseover() and mouseout() instead:
$("img.faded").live("mouseover",function() {
$(this).animate({"opacity": "1"}, "fast");
});
$("img.faded").live("mouseout", function() {
$(this).animate({"opacity": "0.5"}, "fast");
});
... and now it works flawlessly even on the content I fetch from the AJAX-call.
Sorry if anyone has started writing an answer already.
You have to bind the new events each time you add a DOM element to the page.
There is a built-in function in jquery called live that does that for you.
I noticed you add the images from your xml; you can add there the new binds too.
$(xml).find("image").each(function(){
//this actually creates a jquery element that you can work with
$('my-img-code-from-xml-goes-here').hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
}
//i did all my dirty stuff with it, let's add it where it belongs!
).appendTo($('some-already-created-element'));
});
EDIT: corrected a wrong sentence.

Categories