Change option and reinitialize - javascript

I am using jscroll as an infinite scroll pager.
$j('.frontpage').jscroll({
loadingHtml: '<div style="text-align: center;"><img width="50" src="ring-alt-1.gif" alt="Loading" /></div>',
padding: 20,
nextSelector: 'div.next a',
contentSelector: '.latest-container',
autoTrigger: true,
autoTriggerUntil: 1
});
This is a pretty neat plugin and it uses the must-have for my project autoTriggerUntil.
Using that method you can limit the times that the content loads automatic and show the pagination's "next" button.
What I am trying to achieve is this.
Load the first set of posts (actually the 2nd page) with infinite. (DONE)
After the 2nd page, show a "Load All" button. (DONE)
Both 1 and 2 work but what I am trying to do is this: After clicking the "Load All" on page 2, I want to destroy the limiter and get back to an infinite view until the end.
I basically need to reinitialize this somehow. I have been messing with intervals and other bad practices the last couple of hours with no results.

After digging I came out with this solution:-
first, you need to add a callback function like this:-
$('.frontpage').jscroll({
//your existing settings ,
callback: function() {
if ($('div.next a').is(":visible")) {
$('.frontpage').jscroll.destroy();
$('div.next a').off('click');
}
}
});
Second Add onclick attribute to the load All a tag (only in the page where the load all a tag is visible)
onclick="loadAllClick(event);"
and the handler function should be like this:-
<script>
var loadAllClick = function(e) {
e.preventDefault();
$('.frontpage').jscroll( //your settings
);
}
</script>
and Here is a fully working plunker sample
Hope this answers your question

You can use the $(el).off() method and the plugin's callback option.
Tested on the plugin page http://jscroll.com/.
It can look something like this:
var counter = 0;
function scrollerCallback(){
counter++;
if(counter<2){return;}
var el = $j('div.next a'); //Your 'next' selector
el.off()
el.on('click',function(e){
e.preventDefault(); // we don't want the browser to go to redirect
// Add your code to show the rest of the comments here.
});
}
And then call bind the same way but add callback:
$j('.frontpage').jscroll({
loadingHtml: '<div style="text-align: center;"><img width="50" src="ring-alt-1.gif" alt="Loading" /></div>',
...
callback:scrollerCallback,
autoTriggerUntil: 1
});

In your CallBack function, try using this:
var counter = 0;
function scrollerCallback(){
counter++;
if(counter<2){return;}
var el = $j(document).find('div.next a');
el.on('click',function(e){
e.preventDefault();
console.log("This call gets executed!");
$j('.frontpage').jscroll({
autoTrigger: false,
autoTriggerUntil: false
});
});
}
What happens when you do this? I guess you have to modify the library itself for this to work, but I am not quite sure yet ...

Related

Close pretty photo slideshow on click of last slide

I am using pretty photo jquery plugin to display slide show, last slide is 'Enter site', when user click on this slide, slide show should stop and user will be redirected to home page of website. How can I implement this.
I tried to use onclick event of and tag but none of them are getting called. I even tried to register onclick event from jQuery using 'on' function but no luck.
Thanks in advance.
Since the callback function is called when prettyPhoto is closed, you need to use:
changepicturecallback, which is called everytime an item is shown/changed.
In this function you have to read the current item and evaluate if it's the last one.
Try this piece of code:
$("a[rel^='prettyPhoto']").prettyPhoto({
animationSpeed:'normal',
slideshow:5000,
show_title: true,
allow_resize: true,
autoplay_slideshow: true,
social_tools: false,
deeplinking: false,
callback: function(){
console.log('pretty photo is closed')
},
image_markup: '<img id="fullResImage" class="fullResImage" src="{path}" />',
changepicturecallback: function(){
var currentSlide = ($('.pp_gallery').find('li').index($('.selected'))+1);
var myArray = jQuery('.currentTextHolder').text().split('/');
if(currentSlide == myArray[1]){
/* Make redirect to your HP */
}
}
});

Difficulty attaching event handler to dynamically generated modal window elements

This question is an ongoing learning / discovery of these three questions. This issue for me started here:
First Post
Second Post
Now this post is regarding #StephenMuecke post about attaching the event handler dynamically. This was new to me so I had to read up but now I see that it does make sense.
Well after reading documentation and numerous SO posts I still can't seem to get the click event handler to fire??
This time I decided to take a different approach. I created a jsfiddle demonstrating the problem. http://jsfiddle.net/ramjet/93nqs040/17/
However the jsfiddle I had to change somewhat from reality to get it to work within their framework. Below is the actual code.
Parent Window script that launches modal...the alert Bound does fire.
<script>
$(document).ready(function ()
{
$("#new").click(function (e)
{
e.preventDefault();
var ischanging = false;
var financierid = 0;
var detailsWindow = $("#window").data("kendoWindow");
if (!detailsWindow)
{
// create a new window, if there is none on the page
detailsWindow = $("#window")
// set its content to 'loading...' until the partial is loaded
.html("Loading...")
.kendoWindow(
{
modal: true,
width: "800px",
height: "400px",
title: "#T("...")",
actions: ["Close"],
content:
{
url: "#Html.Raw(Url.Action("ActionName", "Controller"))",
data: { financierId: financierid, isChanging: ischanging }
}
})
.data("kendoWindow").bind('refresh', function (e)
{
alert('Bound');
$('document').on("click", "#save", function () { alert("i work");});
}).center();
}
detailsWindow.open();
});
</script>
The modal full html I didn't think was needed but if it is I will update it. This is just the element I am trying to dynamically bind to.
<input type="button" id="save" style="margin-right:10px;" value="Save Record" />
document doesn't need quotes:
$(document).on("click", "#save", function () { alert("i work");});
"document" searches for an element of document, not the actual document
$("document").length; //0
$(document).length; //1

Linking button to jQuery through service

I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code):
Default.aspx
jQuery:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
});
}
jQuery(document).ready(function () {
getContent();
});
HTML:
<div id="content"></div>
ContentService.vb
<WebMethod()> _
Public Function GetContent(number As Integer) As String
Dim sb = New StringBuilder
sb.AppendLine("<table>")
sb.AppendLine("<tr>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>")
sb.AppendLine("</tr>")
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & number & "</td>")
sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
sb.AppendLine("</table>")
Return sb.ToString
End Function
So that's the basics of what I have everything works but I'm not sure how to get the a button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup.
I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page.
$('#test').unbind('click').click(function () {
alert('Working');
});
I'm sure this is easy to do, but I have been trying for a while and cannot seem to get it to work.
Is the problem that you're trying to bind to the element that ISN'T in existance yet?
are you calling the $('#test').unbind('click').click(function () {
alert('Working');
}); BEFORE the service has returned?
$('#test').on('click', function () {
alert('Working');
});
This will bind the event to the '#test' element once it has been inserted in to the DOM.
As you load the content via ajax, you have to bind to $('#content'). Like this:
$(function () {
$('#content').on('click', '#test', function () {
e.preventDefault(); // if a default action is not needed needed
alert('Working');
});
});
I guess this is about not preventing the default behaviour of the A href tag. Now it will probably link to '#' instead of firing the onclick event.
$('#test').on('click', function (e) {
alert('Working');
e.preventDefault();
});
You could try to wrap this in a document ready, or eventually use the .on binder from jQuery, since it's dynamic content.
Solved
It was a very small thing that caused this. The code to fix this problem is as follows:
$('#test').unbind('click').click(test);
This needed to go inside the function with the json so:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
$('#test').unbind('click').click(test);
});
}
Thank you to everyone that has tried to help me.

Redefining a jQuery dialog button

In our application we use a general function to create jQuery dialogs which contain module-specific content. The custom dialog consists of 3 buttons (Cancel, Save, Apply). Apply does the same as Save but also closes the dialog.
Many modules are still using a custom post instead of an ajax-post. For this reason I'm looking to overwrite/redefine the buttons which are on a specific dialog.
So far I've got the buttons, but I'm unable to do something with them. Is it possible to get the buttons from a dialog (yes, I know) but apply a different function to them?
My code so far:
function OverrideDialogButtonCallbacks(sDialogInstance) {
oButtons = $( '#dialog' ).dialog( 'option', 'buttons' );
console.log(oButtons); // logs the buttons correctly
if(sDialogInstance == 'TestInstance') {
oButtons.Save = function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
}
}
}
$('#dialog').dialog({
'buttons' : {
'Save' : {
id:"btn-save", // provide the id, if you want to apply a callback based on id selector
click: function() {
//
},
},
}
});
Did you try this? to override button's callback based on the need.
No need to re-assign at all. Try this.
function OverrideDialogButtonCallbacks(dialogSelector) {
var button = $(dialogSelector + " ~ .ui-dialog-buttonpane")
.find("button:contains('Save')");
button.unbind("click").on("click", function() {
alert("save overriden!");
});
}
Call it like OverrideDialogButtonCallbacks("#dialog");
Working fiddle: http://jsfiddle.net/codovations/yzfVT/
You can get the buttons using $(..).dialog('option', 'buttons'). This returns an array of objects that you can then rewire by searching through them and adjusting the click event:
// Rewire the callback for the first button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons[0].click = function() { alert('Click rewired!'); };
See this fiddle for an example: http://jsfiddle.net/z4TTH/2/
If necessary, you can check the text of the button using button[i].text.
UPDATE:
The buttons option can be one of two forms, one is an array as described above, the other is an object where each property is the name of the button. To rewire the click event in this instance it's necessary to update the buttons option in the dialog:
// Rewire the callback for the OK button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons.Ok = function() { alert('Click rewired!'); };
$('#dialog').dialog('option', 'buttons', buttons);
See this fiddle: http://jsfiddle.net/z4TTH/3/
Can you try binding your new function code with Click event of Save?
if(sDialogInstance == 'TestInstance') {
$('#'+savebtn_id).click(function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
});
}

Number, hover (etc) effect not work after Ajax Load More

I'm using Drupal 7 and get my content with View module on page. And my pager Views Load More module. And my thumbnail effect hover, shadow etc. Image hover using this code:
var hoverImg = '<div class="hoverimg"></div>';
$(".thumb").each(function(){
$(this).children("div").each(function(){
$(this).find("a").append(hoverImg);
});
});
$(".thumb div").hover(function() {
$(this).find(".hoverimg").animate({ opacity: 'toggle' });
});
$(".thumb").hover(function() {
$(this).find("div").each(function(){
$(this).find(".shadow").fadeOut(500);
});
});
And getting number on my current thumbnail. This code:
var c = '';
var d = '';
$('.view-content div.views-row').each(function(){
c = 0;
d = 0;
var i = 1;
d = $(this).find('.thumbimg').length;
$(this).find('.thumbimg').each(function(){
sayi=i++;
$(this).append('<div class="img_no">0'+sayi+'</div>');
});
});
Everything is OK. All effects on start page. But when click Load More button, my effects can't work another page.
How do i solve this problem? Thanks.
The reason why it stops working is due to the hover function (and your other scripts/functions) only works on existing elements. So if you add something with ajax, it wont apply to that unless you reload the script after the ajax load.
Another option is to use live() or on() (for the hover part. On is the new version of live, added in jQuery 1.7).
Live and on listens for any existing or future elements.
A live script would look something like this:
$(".yourElement").live({
mouseenter:
function () {
// Do something
},
mouseleave:
function () {
// Do something
},
mousemove:
function () {
// Do something
}
});

Categories