Using reCaptcha3 Without Forms? - recaptcha

I need to clear up what may be a potential misunderstanding between me and the recaptcha library.
All of the examples that I have seen from searching around and finding YouTube videos of the v3 implementation have been attaching the recaptcha ready/execute functions within the context of a <form>... but I am trying to use reCaptcha outside the context of a <form> in the following way:
A user enters a name or a portion of their name into a search box
The frontend, after a delay of input or the enter key, gets names in the system which match this input (partial or full)
The results are loaded into a drop-down that auto-populates.
The user selects the appropriate name through either clicking or arrowing down, and this searches for specific data about that user.
If I can figure out how to get the reCaptcha token to take place on the name dropdown search, I will be able to extend that solution to the fourth point... but I am afraid that it may not be possible.
All code below is JavaScript:
Relevant Bits
Listener on search field:
$(".web-search-content").on("keyup", ".searchField", function(e) {
if (
e.keyCode != 40 &&
e.keyCode != 38 &&
e.keyCode != 13 &&
e.keyCode != 27
) {
delayCall($(this), 800, nameSearch, e);
} else if (e.keyCode == 27) {
$(".name-search-results").remove();
}
});
nameSearch function:
function nameSearch(obj, e) {
if (!e) {
e = window.event;
}
var container = $(".name-search-results");
if (
e.keyCode != 40 &&
e.keyCode != 38 &&
e.keyCode != 13 &&
e.keyCode != 27
) {
var field = obj;
var value = field.val();
if (value != undefined && value.length > 0) {
var captchaToken = "";
grecaptcha.execute('<REDACTED>', {action: 'webSearch/nameSearch'}).then(function(token) {
captchaToken = token;
console.log(captchaToken);
document.getElementById("g-recaptcha-response").value = token;
})
$.post("../webSearch/nameSearch", { query: value, captchaToken: captchaToken }, function(resp) {
showNameResults(resp);
});
} else {
container.remove();
}
}
}
Can someone confirm that reCaptcha v3 must be used within the context of a form, or can it handle events like this... and if so, how?

reCAPTCHA v3 is not tied to a form submission. From the docs:
reCAPTCHA v3 will never interrupt your users, so you can run it whenever you like without affecting conversion. reCAPTCHA works best when it has the most context about interactions with your site, which comes from seeing both legitimate and abusive behavior. For this reason, we recommend including reCAPTCHA verification on forms or actions as well as in the background of pages for analytics.
Note: You can execute reCAPTCHA as many times as you'd like with different actions on the same page.
So, you don't need to wait for the user to submit the form to run reCAPTCHA. Instead, you can make the call in the background for different actions across the site. Store the returned score and then check that on form submission to decide what action you want to take.
// Decide what score you want to allow as a pass
const threshold = 0.5;
// Set up a variable
let score = null;
// Call reCAPTCHA on page load
grecaptcha.ready(function () {
grecaptcha.execute('[redacted]', { action: 'pages/search' }).then(function (token) {
// Create an endpoint on your server to validate the token and return the score
fetch('/recaptcha-verify?action=pages/search&token=' + token).then(function (response) {
response.json().then(function (data) {
score = data.score;
});
});
});
});
// Later, e.g. in the form submission just check if the score is above the threshold
if (score >= threshold) {
// success
submitForm();
} else {
// score too low
doSomethingElse();
}
This is the approach used here:
https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php
https://github.com/google/recaptcha/blob/master/examples/recaptcha-v3-request-scores.php

Related

Shopify: Checkout ajax validations?

I need to add ajax validations in the checkout page when the users click on the Continue button in each checkout step. Does anyone know if this is possible?
I need to send the Cart object, Address, items, etc. The idea is, the users are unable to continue, if they fail the validation.
You can only do this if you are on Shopify Plus. You cannot inject Javascript into checkout for the very good reason that you'd probably break it! It is a finely tuned machine, so the most you can do usually is change some css classes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you have Shopify Plus, then you can insert your js form validation.
Also you have to replace the given input id with you custom id. After which, you can insert, check and get data from input fields
Below is script for phone number validation
$("#checkout_shipping_address_phone").attr("id","checkout_shipping_address_phone_clone");
document.getElementById('checkout_shipping_address_phone_clone').setAttribute('maxlength','10');
document.getElementById('checkout_shipping_address_phone_clone').setAttribute('max-length','10');
// document.getElementById('checkout_shipping_address_phone').setAttribute('type','number');
// document.getElementById('checkout_shipping_address_phone').setAttribute('minlength','10');
// document.getElementById('checkout_shipping_address_phone').setAttribute('data-minlength','10');
let mobileBtn = document.getElementById('checkout_shipping_address_phone_clone');
mobileBtn.removeAttribute('aria-required');
mobileBtn.removeAttribute('data-phone-formatter-country-select');
mobileBtn.removeAttribute('data-phone-formatter');
mobileBtn.removeAttribute('autocomplete');
mobileBtn.setAttribute("onkeypress","return isNumber(event)");
mobileBtn.type='text';
console.log("aaa");
function isNumber(evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
$("body").on("click","#continue_button",function(){
var hh = $('#checkout_shipping_address_phone_clone').val();
if(hh.length==10){
console.log('dbcjhsdvjhdsvhjsjh');
$("#error_msgehh").remove();
$('#continue_button').attr('type','submit');
$('#continue_button').css('opacity','1');
}
else{
console.log(hh.length);
$('#continue_button').css('opacity','.5');
$("#error_msgehh").remove();
$('#checkout_shipping_address_phone_clone').parent().after().append('<p id="error_msgehh" style="color:red;">Enter 10 Digit Phone Number</p>');
$('#continue_button').attr('type','button');
}
});
$('#checkout_shipping_address_phone_clone').attr('maxlength','10');
$('#checkout_shipping_address_phone_clone').attr('max-length','10');
$("body").on("keyup mouseenter mouseleave","#checkout_shipping_address_phone_clone",function(){
var hh = $(this).val();
const regexExp = /^[6-9]$/gi;
let firstChar = regexExp.test(hh[0]); // dont allow 0,1,2,3,4,5 digits at first place
if(!firstChar){
var v ='';
$('#checkout_shipping_address_phone_clone').val(v);
}
});
$("body").on("keyup mouseenter mouseleave",".field__input-wrapper input",function(){
var hh = $('#checkout_shipping_address_phone_clone').val();
console.log('hover');
const regexExp = /^[6-9]$/gi;
let firstChar = regexExp.test(hh[0]); // dont allow 0,1,2,3,4,5 digits at first place
if(!firstChar){
var v ='';
$('#checkout_shipping_address_phone_clone').val(v);
}
});
// console.log("bbbaaa");
// });

How to tell if a cell value has passed validation

I am familiar with the Google Apps script DataValidation object. To get and set validation criteria. But how to tell programatically if a cell value is actually valid. So I can see the little red validation fail message in the spreadsheet but can the fact the cell is currently failing validation be picked up thru code?
I have tried to see if there is a cell property that tells you this but there is not. Also I looked for some sort of DataValidation "validate" method - i.e. test a value against validation rules, but nothing there either
Any ideas? Is this possible??
Specific answer to your question, there is no method within Google Apps Script that will return the validity of a Range such as .isValid(). As you state, you could reverse engineer a programatic one using Range.getDataValidations() and then parsing the results of that in order to validate again the values of a Range.getValues() call.
It's a good suggestion. I've added a feature request to the issue tracker -> Add a Star to vote it up.
I've created a workaround for this issue that works in a very ugly -technically said- and slightly undetermined way.
About the workaround:
It works based on the experience that the web browser implementation of catch() function allows to access thrown errors from the Google's JS code parts.
In case an invalid input into a cell is rejected by a validation rule then the system will display an error message that is catchable by the user written GAS. In order to make it work first the reject value has to be set on the specified cell then its vale has to be re-entered (modified) then -right after this- calling the getDataValidation() built in function allows the user to catch the necessary error.
Only single cells can be tested with this method as setCellValues() ignores any data validation restriction (as of today).
Disadvantages:
The validity won't be necessarily re-checked for this function:
it calls a cell validation function right after the value is inserted into the cell.
Therefore the result of this function might be faulty.
The code messes up the history as cells will be changed - in case they are
valid.
I've tested it successfully on both Firefox and Chromium.
function getCellValidity(cell) {
var origValidRule = cell.getDataValidation();
if (origValidRule == null || ! (cell.getNumRows() == cell.getNumColumns() == 1)) {
return null;
}
var cell_value = cell.getValue();
if (cell_value === '') return true; // empty cell is always valid
var is_valid = true;
var cell_formula = cell.getFormula();
// Storing and checking if cell validation is set to allow invalid input with a warning or reject it
var reject_invalid = ! origValidRule.getAllowInvalid();
// If invalid value is allowed (just warning), then changing validation to reject it
// IMPORTANT: this will not throw an error!
if (! reject_invalid) {
var rejectValidRule = origValidRule.copy().setAllowInvalid(false).build();
cell.setDataValidation(rejectValidRule);
}
// Re-entering value or formula into the cell itself
var cell_formula = cell.getFormula();
if (cell_formula !== '') {
cell.setFormula(cell_formula);
} else {
cell.setValue(cell_value);
}
try {
var tempValidRule = cell.getDataValidation();
} catch(e) {
// Exception: The data that you entered in cell XY violates the data validation rules set on this cell.
// where XY is the A1 style address of the cell
is_valid = false;
}
// Restoring original rule
if (rejectValidRule != null) {
cell.setDataValidation(origValidRule.copy().setAllowInvalid(true).build());
}
return is_valid;
}
I still recommend starring the above Google bug report opened by Jonathon.
I'm using this solution. Simple to learn and fast to use! You may need to adapt this code for your needs. Hope you enjoy
function test_corr(link,name) {
var ss = SpreadsheetApp.openByUrl(link).getSheetByName(name);
var values = ss.getRange(2,3,200,1).getValues();
var types = ss.getRange(2,3,200,1).getDataValidations()
var ans
for (var i = 0; i < types.length; i++) {
if (types[i][0] != null){
var type = types[i][0].getCriteriaType()
var dval_values = types[i][0].getCriteriaValues()
ans = false
if (type == "VALUE_IN_LIST") {
for (var j = 0; j < dval_values[0].length; j++) {
if (dval_values[0][j] == values[i][0]) { ans = true }
}
} else if (type == "NUMBER_BETWEEN") {
if (values[i][0] >= dval_values[0] && values[i][0] <= dval_values[1]) { ans = true }
} else if (type == "CHECKBOX") {
if (values[i][0] == "Да" || values[i][0] == "Нет") { ans = true }
}
if (!ans) { return false }
}
}
return true;
}

Tracking with Java Script if Ajax request is going on in a webpage or Intercept XMLHttpRequest through Selenium Web driver

I am using Selenium WebDriver for crawling a web site(only for example, I will be crawling other web sites too!) which has infinite scroll.
Problem statement:
Scroll down the infinite scroll page till the content stops loading using Selenium web driver.
My Approach:
Currently I am doing this-
Step 1: Scroll to the page bottom
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.onload=toBottom();"+
"function toBottom(){" +
"window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
"document.body.scrollHeight,document.documentElement.clientHeight));" +
"}");
Then I wait for some time to let the Ajax Request complete like this-
Step 2: Explicitly wait for Ajax request to be over
Thread.sleep(1000);
Then I give another java script to check if the page is scrollable
Step 3:Check if the page is scrollable
//Alternative to document.height is to be used which is document.body.clientHeight
//refer to https://developer.mozilla.org/en-US/docs/DOM/document.height
if((Long)js.executeScript("return " +
"(document.body.clientHeight-(window.pageYOffset + window.innerHeight))")>0)
If the above condition is true then I repeat the from Step 1 - 3, till condition in Step 3 is false.
The Problem:
I do not want to give the Thread.sleep(1000); in step 2, rather I would like to check using Java Script if the background Ajax request is over and then scroll down further if the condition in Step 3 is true .
PS: I am not the developer of the page so I do not have access to the code running the page, I can just inject java scripts(as in Step 1 and 3) in the web page. And, I have to write a generic logic for any web site with Ajax requests during infinite scroll.
I will be grateful to some one could spare some time here!
EDIT : Ok, after struggling for 2 days, I have figured out that the pages which I am crawling through the Selenium WebDriver can have any of these JavaScript libraries and I will have to pool according to the different Library, for example, In case of the web application using jQuery api, I may be waiting for
(Long)((JavascriptExecutor)driver).executeScript("return jQuery.active")
to return a zero.
Likewise if the web application is using the Prototype JavaScript library I will have to wait for
(Long)((JavascriptExecutor)driver).executeScript("return Ajax.activeRequestCount")
to return a zero.
Now, the problem is how do I write a generic code which could handle most the JavaScript libraries available?
Problem I am facing in implementing this-
1. How do I find which JavaScript Library is being used in the Web Application(using Selenium WebDriver in Java), such that I can then write the corresponding wait methods?
Currently, I am using this
Code
2. This way I will have to write as many as 77 methods for separate JavaScript library so, I need a better way to handle this scenario as well.
In short, I need to figure out if the browser is making any call(Ajax or simple) with or without any JavaScript library through Selenium Web Driver's java implementation
PS: there are Add ons for Chorme's JavaScript Lib detector and Firefox's JavaScript Library detector which detect the JavaScript library being used.
For web pages with Ajax Response during the infinite scroll and using jQuery API(or other actions), before starting to opening the web page.
//Inject the pooling status variable
js.executeScript("window.status = 'fail';");
//Attach the Ajax call back method
js.executeScript( "$(document).ajaxComplete(function() {" +
"status = 'success';});");
Step 1: will remain the same as in the original question
Step 2 Pooling the following script(This is the one which removes the need of Thread.Sleep() and makes the logic more dynamic)
String aStatus = (String)js.executeScript("return status;");
if(aStatus!=null && aStatus.equalsIgnoreCase("success")){
js.executeScript("status = 'fail';");
break poolingLoop;
}
Step 3: No need now!
Conclusion: No need to give blunt Thread.sleep(); again and again while using Selenium WebDriver!!
This approach works good only if there's jQuery api being used in the web application.
EDIT:
As per the the link given by #jayati i injected the javascript-
Javascript one:
//XMLHttpRequest instrumentation/wrapping
var startTracing = function (onnew) {
var OldXHR = window.XMLHttpRequest;
// create a wrapper object that has the same interfaces as a regular XMLHttpRequest object
// see http://www.xulplanet.com/references/objref/XMLHttpRequest.html for reference on XHR object
var NewXHR = function() {
var self = this;
var actualXHR = new OldXHR();
// private callbacks (for UI):
// onopen, onsend, onsetrequestheader, onupdate, ...
this.requestHeaders = "";
this.requestBody = "";
// emulate methods from regular XMLHttpRequest object
this.open = function(a, b, c, d, e) {
self.openMethod = a.toUpperCase();
self.openURL = b;
ajaxRequestStarted = 'open';
if (self.onopen != null && typeof(self.onopen) == "function") {
self.onopen(a,b,c,d,e); }
return actualXHR.open(a,b,c,d,e);
}
this.send = function(a) {
ajaxRequestStarted = 'send';
if (self.onsend != null && typeof(this.onsend) == "function") {
self.onsend(a); }
self.requestBody += a;
return actualXHR.send(a);
}
this.setRequestHeader = function(a, b) {
if (self.onsetrequestheader != null && typeof(self.onsetrequestheader) == "function") { self.onsetrequestheader(a, b); }
self.requestHeaders += a + ":" + b + "\r\n";
return actualXHR.setRequestHeader(a, b);
}
this.getRequestHeader = function() {
return actualXHR.getRequestHeader();
}
this.getResponseHeader = function(a) { return actualXHR.getResponseHeader(a); }
this.getAllResponseHeaders = function() { return actualXHR.getAllResponseHeaders(); }
this.abort = function() { return actualXHR.abort(); }
this.addEventListener = function(a, b, c) { return actualXHR.addEventListener(a, b, c); }
this.dispatchEvent = function(e) { return actualXHR.dispatchEvent(e); }
this.openRequest = function(a, b, c, d, e) { return actualXHR.openRequest(a, b, c, d, e); }
this.overrideMimeType = function(e) { return actualXHR.overrideMimeType(e); }
this.removeEventListener = function(a, b, c) { return actualXHR.removeEventListener(a, b, c); }
// copy the values from actualXHR back onto self
function copyState() {
// copy properties back from the actual XHR to the wrapper
try {
self.readyState = actualXHR.readyState;
} catch (e) {}
try {
self.status = actualXHR.status;
} catch (e) {}
try {
self.responseText = actualXHR.responseText;
} catch (e) {}
try {
self.statusText = actualXHR.statusText;
} catch (e) {}
try {
self.responseXML = actualXHR.responseXML;
} catch (e) {}
}
// emulate callbacks from regular XMLHttpRequest object
actualXHR.onreadystatechange = function() {
copyState();
try {
if (self.onupdate != null && typeof(self.onupdate) == "function") { self.onupdate(); }
} catch (e) {}
// onreadystatechange callback
if (self.onreadystatechange != null && typeof(self.onreadystatechange) == "function") { return self.onreadystatechange(); }
}
actualXHR.onerror = function(e) {
ajaxRequestComplete = 'err';
copyState();
try {
if (self.onupdate != null && typeof(self.onupdate) == "function") { self.onupdate(); }
} catch (e) {}
if (self.onerror != null && typeof(self.onerror) == "function") {
return self.onerror(e);
} else if (self.onreadystatechange != null && typeof(self.onreadystatechange) == "function") {
return self.onreadystatechange();
}
}
actualXHR.onload = function(e) {
ajaxRequestComplete = 'loaded';
copyState();
try {
if (self.onupdate != null && typeof(self.onupdate) == "function") { self.onupdate(); }
} catch (e) {}
if (self.onload != null && typeof(self.onload) == "function") {
return self.onload(e);
} else if (self.onreadystatechange != null && typeof(self.onreadystatechange) == "function") {
return self.onreadystatechange();
}
}
actualXHR.onprogress = function(e) {
copyState();
try {
if (self.onupdate != null && typeof(self.onupdate) == "function") { self.onupdate(); }
} catch (e) {}
if (self.onprogress != null && typeof(self.onprogress) == "function") {
return self.onprogress(e);
} else if (self.onreadystatechange != null && typeof(self.onreadystatechange) == "function") {
return self.onreadystatechange();
}
}
if (onnew && typeof(onnew) == "function") { onnew(this); }
}
window.XMLHttpRequest = NewXHR;
}
window.ajaxRequestComplete = 'no';//Make as a global javascript variable
window.ajaxRequestStarted = 'no';
startTracing();
Or Javascript Two:
var startTracing = function (onnew) {
window.ajaxRequestComplete = 'no';//Make as a global javascript variable
window.ajaxRequestStarted = 'no';
XMLHttpRequest.prototype.uniqueID = function() {
if (!this.uniqueIDMemo) {
this.uniqueIDMemo = Math.floor(Math.random() * 1000);
}
return this.uniqueIDMemo;
}
XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open;
var newOpen = function(method, url, async, user, password) {
ajaxRequestStarted = 'open';
/*alert(ajaxRequestStarted);*/
this.oldOpen(method, url, async, user, password);
}
XMLHttpRequest.prototype.open = newOpen;
XMLHttpRequest.prototype.oldSend = XMLHttpRequest.prototype.send;
var newSend = function(a) {
var xhr = this;
var onload = function() {
ajaxRequestComplete = 'loaded';
/*alert(ajaxRequestComplete);*/
};
var onerror = function( ) {
ajaxRequestComplete = 'Err';
/*alert(ajaxRequestComplete);*/
};
xhr.addEventListener("load", onload, false);
xhr.addEventListener("error", onerror, false);
xhr.oldSend(a);
}
XMLHttpRequest.prototype.send = newSend;
}
startTracing();
And checking the status of the status vars ajaxRequestStarted, ajaxRequestComplete in the java code, one can determine if the ajax was started or completed.
Now I have a way to wait till an Ajax is complete, I can also find if the Ajax was triggered on some action
Approach 1:
Your approach is good, just a few changes would do the trick:
Step 1: Improve this step to call the toBottom function at regular interval using window.setInterval. At (c >= totalcount) call window.clearInterval
Setp 2: Instead of checking the page is yet scrollable, check if (c >= totalcount). And this condition every 200ms until (c >= totalcount) returns true.
FYI: If the Step 1 doesn't work in all the browsers then probably, you can refer to line 5210 of Tata-Nano-Reviews-925076578.js and call this with cvariable checking.
Approach 2:
Go to jQuery API and type "ajax". You can find some callback handlers which could be used for ajax requests.
Probably, set a variable before the request is been sent and after it is been received appropriately.
And in between use your original method of scrolling to bottom at regular interval, unless you can no more scroll. At this point clear the interval variable.
Now, regularly check if that interval variable is null or not. Null would mean that you have reached the bottom.
We had to solve the same problem, and managed using a long Javascript function. Just need to add checks to see which library is not undefined.
PS Thanks for giving me an easy answer for how to check for in progress Prototype requests!
eg. Handle JQuery and XHR/Prototype
var jsExecutor = /*Get your WebDriverInstance*/ as IJavaScriptExecutor;
while(/*your required timeout here*/)
{
var ajaxComplete =
jsExecutor.ExecuteScript("return ((typeof Ajax === 'undefined') ||
Ajax.activeRequestCount == 0) && ((typeof jQuery === 'undefined') || $.active == 0)");
if (ajaxIsComplete)
return
}

Less CSS and local storage issue

I'm using LESS CSS (more exactly less.js) which seems to exploit LocalStorage under the hood. I had never seen such an error like this before while running my app locally, but now I get "Persistent storage maximum size reached" at every page display, just above the link the unique .less file of my app.
This only happens with Firefox 12.0 so far.
Is there any way to solve this?
P.S.: mainly inspired by Calculating usage of localStorage space, this is what I ended up doing (this is based on Prototype and depends on a custom trivial Logger class, but this should be easily adapted in your context):
"use strict";
var LocalStorageChecker = Class.create({
testDummyKey: "__DUMMY_DATA_KEY__",
maxIterations: 100,
logger: new Logger("LocalStorageChecker"),
analyzeStorage: function() {
var result = false;
if (Modernizr.localstorage && this._isLimitReached()) {
this._clear();
}
return result;
},
_isLimitReached: function() {
var localStorage = window.localStorage;
var count = 0;
var limitIsReached = false;
do {
try {
var previousEntry = localStorage.getItem(this.testDummyKey);
var entry = (previousEntry == null ? "" : previousEntry) + "m";
localStorage.setItem(this.testDummyKey, entry);
}
catch(e) {
this.logger.debug("Limit exceeded after " + count + " iteration(s)");
limitIsReached = true;
}
}
while(!limitIsReached && count++ < this.maxIterations);
localStorage.removeItem(this.testDummyKey);
return limitIsReached;
},
_clear: function() {
try {
var localStorage = window.localStorage;
localStorage.clear();
this.logger.debug("Storage clear successfully performed");
}
catch(e) {
this.logger.error("An error occurred during storage clear: ");
this.logger.error(e);
}
}
});
document.observe("dom:loaded",function() {
var checker = new LocalStorageChecker();
checker.analyzeStorage();
});
P.P.S.: I didn't measure the performance impact on the UI yet, but a decorator could be created and perform the storage test only every X minutes (with the last timestamp of execution in the local storage for instance).
Here is a good resource for the error you are running into.
http://www.sitepoint.com/building-web-pages-with-local-storage/#fbid=5fFWRXrnKjZ
Gives some insight that localstorage only has so much room and you can max it out in each browser. Look into removing some data from localstorage to resolve your problem.
Less.js persistently caches content that is #imported. You can use this script to clear content that is cached. Using the script below you can call the function destroyLessCache('/path/to/css/') and it will clear your localStorage of css files that have been cached.
function destroyLessCache(pathToCss) { // e.g. '/css/' or '/stylesheets/'
if (!window.localStorage || !less || less.env !== 'development') {
return;
}
var host = window.location.host;
var protocol = window.location.protocol;
var keyPrefix = protocol + '//' + host + pathToCss;
for (var key in window.localStorage) {
if (key.indexOf(keyPrefix) === 0) {
delete window.localStorage[key];
}
}
}

Waypoint unrecognized on Ajax-loaded content

I'm loading a page into a div. I'm also attempting to establish a waypoint, so that when the user scrolls down the page, the menu will change colors.
The problem I am having is the new height of the div is not recognized by the browser once the ajax content is loaded.
Here's what I have:
$(".cta").live('click', function () {
$('#faq').load('about-us/faqs/index.html'),
function () {
$("#faq").waypoint(function (event, direction) {
if (direction === 'up') {
$("#siteNav li a").removeClass("siteNavSelected");
$("#siteNav li.nav3 a").addClass("siteNavSelected");
}
}, {
offset: function () {
return $.waypoints('viewportHeight') - $("#faq").outerHeight();
}
});
}
return false;
});
Any ideas? Thanks.
Use $.waypoints('refresh');, from the documentation:
This will force a recalculation of each waypoint’s trigger point based on its offset option. This is called automatically whenever the window is resized or new waypoints are added. If your project is changing the DOM or page layout without doing one of these things, you may want to manually call it.
I'm not familiar with the intrinsics of the waypoint plugin, but you could also bind a scroll event and then capture the .scrollTop() value. Would look something like this:
$(document).bind('scroll', function(event) {
var scrollTop = $(window).scrollTop();
if (scrollTop < 1000 && $('siteNav li').hasClass('styleA')) { return; }
else {
$('siteNav li').removeClass('styleB');
$('siteNav li').addClass('styleA');
}
if (scrollTop > 1000 && $('siteNav li').hasClass('styleB')) { return; }
else {
$('siteNav li').removeClass('styleA');
$('siteNav li').addClass('styleB');
}
});
You have to play with the values a little to get it acting at the right spot. Also you have to use a greater or less than value in the test as if a user is at the top of the page and uses the scroll-wheel on his mouse to fly down the page, you don't get every value in between.

Resources