Good day folks. I need to figure out how to perform an action using Ajax once I have linked to a specific section on a page. I already know how to get to the designated DOM element on the other page, but I would like to go further as to perform some action using ajax once it has taken the visitor to that point.
eg.
<nav>
<ul><li></li></ul>
</nav>
Will take me to this about.php page to the "team" div
<div>
<div><a name="team"></a></div>
</div>
But then I would like to run some Ajax automatically that would usually be executed when the user clicks on some object in the "team" div. So should the user get to this section by way of the link up above, it will take them straight to the content. Does that make sense?
I'm going to go out on a limb and assume you're using jQuery's animate() for the scrolling:
$('html, body').animate(
{ scrollTop: $("#something").offset().top },
1000,
function() {
someAjaxFunction();
}
);
var someAjaxFunction = function() {
$.ajax({
url: '/something/'
}).done(function(data) {
// Done!
});
};
We're using the callback function argument given to animate() to fire off our ajax request.
You can use jQuery's scrollTo() to scroll to the area on the page, then use the complete function to call you ajax after the scroll has finished.
Detailed Description here
$('body').scrollTo('#target', function()
{
// Do your AJAX Thaaang
});
This check can be run to determine if the user has navigated directly to the teamDiv. Running it on page load would allow you to catch it in the event that the user was deep linked to the teamDiv from another page:
if (/#team/.test(window.location.href)) { // perform Ajax query here... }
Note: In the example link, you use the id team whereas the div's ID attribute is set to teamDiv. They need to be the same for this to work.
So the code would run if the user clicks some object in the "team" div?
In that case, is this an option?
<div>
<div id="teamDiv"><a name="team"></a>some element</div>
</div>
<script type="text/javascript">
$(function() {
$("#teamDiv").click(function() {
//put what you want to happen when the user clicks something in
//teamDiv here
});
})
</script>
My suggestion would be to read the current loaded url:
$(document).ready(function () {
var location = window.location.href;
if(location.indexOf('#team' > -1) {
// do something
}
}
You can check location.hash (http://www.w3schools.com/jsref/prop_loc_hash.asp) to determine if hash existed.
If you want to do something in each variants of navigation to this div: click and scroll you can use something like this:
$(document).bind('scroll', function() {
if($(this).scrollTop() > $('.your-div').top()) {
alert('do something');
}
})
Related
I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}
Trying to launch a click event of .register-btn a nav item when visiting a given URL, but not allow the browser to visit that URL.
So, home.com/memberlogin would remain on home.com ( or redirect to home.com if I must ), and proceed to activate the click of a button.
This is what I have so far, which redirects nowhere as that ended up taking longer than the click event, and it also was quite messy having to load the 404, then wait, then redirect, then wait, then wait for the click event.
I would like something clean and smooth if possible.
jQuery(document).ready(function() {
jQuery(function() {
switch (window.location.pathname) {
case '/memberlogin':
jQuery('.register-btn a').trigger( "click" );
return False;
}
});
});
Probably explained it dreadfully so apologies all - the .register-btn a already exists so I can't create this element, I simply wish to trigger the click for it when visiting a URL/link. Open to suggestions but I assumed something like /memberlogin would suffice, then the link would trigger. The snag is I don't want to "visit" that URL, but use it for the trigger only.
Open to an easier way and tell me if I am asking for something that doesn't work, just figured there must be a way.
Have you tried e.preventDefault() ?
click
and the jQuery:
$('.dontGo').on('click',function(e){
e.preventDefault();
//do stuff
})
fiddle: https://jsfiddle.net/b9x7x4m6/
docs: http://www.w3schools.com/jquery/event_preventdefault.asp
A full javascript solution is (snippet updated as asked):
window.onload = function () {
[].slice.call(document.querySelectorAll('.dontGo')).forEach(function(element, index) {
element.addEventListener('click', function(e) {
e.preventDefault();
alert(e.target.textContent);
}, false);
});
// in order to target a specific URL you may write code like in reported,
// assuming the result is only one element,
// otherwise you need to use the previous [].slice.call(documen.....:
document.querySelectorAll('.dontGo[href="linkedin.com"]')[0].addEventListener('click', function(e) {
e.preventDefault();
alert('Linkedin anchor: ' + e.target.textContent);
}, false);
};
stackoverflow <br/>
google <br/>
linkedin <br/>
twitter <br/>
The querySelector let you select elements in a lot of different ways:
if you need to select an anchor with a specific href value you can write:
document.querySelectorAll('.dontGo[href="linkedin.com"]')
Remember, always, that the result of querySelectorAll is a NodeList array. You can test against the length of such array in order to get, just for instance, only the second element if it exists, like:
var nodEles = document.querySelectorAll('.dontGo[href="linkedin.com"]');
if (nodEles.length > 1) {
nodEles[1]......
}
or you can use the format:
[].slice.call(...).forEach(....
to convert the NodeList to a normal array and than apply the event listener for each element.
Yes, you may prefix the href attribute of anchor tag with an hash (#) to avoid page redirecting. But, in this case, the hash tag is used to jump in another page section and this will change your url.
Simply create a function
function theAction(){
return false;
}
Then your link will be
page name
On my blog theme I have a "SHOW MORE POST" button after the last post of the page.
When the user clicks the button, more posts are loaded without refreshing the page.
I am doing this using the "Ajax Load More" plugin from the Wordpress repository.
When there are no more post to load, I would like to hide this button.
When there are no more posts, the button becomes a class of ".done", added by ajax.
I have been trying to hide the button using jQuery like this:
jQuery(document).ready(function($) {
var morebutton = $("button#load-more");
if ( $(morebutton).hasClass("done") ) {
$(this).hide();
}
});
but I am having no result. I think i have the right selectors. I have tryed to hide it on a click and it works. I used this jquery:
jQuery(document).ready(function($) {
var morebutton = $("button#load-more");
$(morebutton).click(function(){
if ( $(this).hasClass("done") ) {
$(this).hide();
}
});
});
So, my question is how can I check if an element hasClass, if this class is dynamically added with AJAX?
When I use the document.ready function it will check my element only on document.ready. Is this correct?
So how could i check also after an ajax event?
Any other ways to hide the button after all posts are loaded?
Thank you!
morebutton is already a jquery object, so, you don't need to wrap again.
$(function() {
var morebutton = $("button#load-more");
morebutton.click(function(){
if ( $(this).hasClass("done") ) {
$(this).hide();
}
});
});
If I understand you right, you want to do this when ajax is done, so you should do this, in the ajax success or done:
$.ajax({
url: whatever
})
.done(function( data ) {
var morebutton = $("#load-more");
//if ( morebutton.hasClass("done") ) { it is done now, check for something else, or just hide
morebutton.hide();
//}
});
You could define a global success like this:
$(document).ajaxSuccess(function() {
var morebutton = $("#load-more");
if ( morebutton.hasClass("done") ) {
morebutton.hide();
}
});
see here for more information: https://api.jquery.com/ajaxSuccess/
Well, it turns out i was trying to make it much more complicated than it had to be.
Instead of using jQuery i just used CSS.
I added a rule like this:
#load-more.done {
display: none;
}
...and now it's working nicely!
Thanks for your help, though! =)
I have a few pages, like a1.html, a2.html, a3.html, a4.html, a5.html....
All pages HTML Markup looks like
<div class="wrap">
<header>Header 2</header>
<saection>Section 2</section>
<footer>
<div class="hover"></div>
</footer>
</div>
so when onhover a1.html .hover class, then page loads a2.html .wrap and appendTo a1.html's body, on the same page, now we have a2.html's contents. when on hover a2.html 's '.hover' (still on a1.html) then loads a3.html's contents and so forth
$('.hover').on('mouseover', function(){
$.get( "/a2.html", function( data ){
///a2.html should be a variable
$('section', data).appendTo('body');
});
});
My question is how to just load a2.html, a3.html or a4.html contents just once when onhover .hover class. How do I test if a2.html is already loaded then, do not load it again? Thanks
Try something like that.
$('.hover').on('mouseover', function(){
if (!$(this).data('active')) {
$(this).data('active', true);
$.get( "/a2.html", function( data ){
///a2.html should be a variable
$('section', data).appendTo('body');
});
}
});
Using the data-set to store a flag (active here), let you the possibility to remove it later and to process again the handler instructions.
If you really want to load it once (and never ever later), replace on by one in your code (as told by #SSS).
$('.hover').one('mouseover', function(){
$.get( "/a2.html", function( data ){
///a2.html should be a variable
$('section', data).appendTo('body');
});
});
Be careful : the way you are using on (or one) binds the mouseover event only on existing DOM elements.
If you want to affect all existing and future DOM elements. You got to use it this way :
$('body').on('mouseover', '.hover', function(){
/// your instructions
});
Hope that will help.
The simplest way is $(..).one(event, handler). But what if you really need to do something after loading once and only once in an a asynchronized and promised way?
I have implemented a cards ui application facing the same problem: card defined in another html file which must be loaded and only once before update/show its content. My resolution is based on jQuery Promises API and a simple cache. Wish helpful and here is part of my code (the real one is much more complicated):
function expect(proc) {
var cache = {};
return function(key) {
if (!cache[key]) {
cache[key] = $.Deferred(function(deferred) {proc(deferred, key); })
.promise();
}
return cache[key];
};
}
var cards = expect(function(deferred, url) {
var $loader = $('div');
function whenDone() {
deferred.resolve(loader.contents());
}
$loader.load(url).then(whenDone);
});
cards('MyCard.html').done(function(contents) {
// It is promised that MyCard is loaded, do what you want here
});
I am currently using jQuery-Smooth-Scroll to smoothly scroll up and down to various anchor positions on one of my pages (Page 1). However, what I would also like to be able to do is, from another page (Page 2), link to Page1 (appending #bookmark to the url) and have jQuery-Smooth-Scroll pick up on the fact I am calling the page with a #bookmark and have it smoothly scroll down to the relevant position once the page has completed loading. I don't know if this is a possibility or not?
This is the version of Smooth-Scroll that I'm using:
https://github.com/kswedberg/jquery-smooth-scroll
I'm still relatively new to jQuery so I may be overlooking something obvious.
Ajma's answer should be sufficient, but for completeness:
alert(location.hash)
Edit: a more complete example:
// on document.ready {
if (location.hash != '') {
var a = $("a[name=" + location.hash.substring(1) + "]");
// note that according to w3c specs, the url hash can also refer to the id
// of an element. if so, the above statement becomes
// var a = $(location.hash);
if (a.length) {
$('html,body').animate({
scrollTop: $(a).offset().top
}, 'slow');
}
}
// }
It's possible, you want to put a call into the smooth scroll function when the page is finished loading. in jQuery, it's using $(document).ready(function () { your code } );
You'll need to put something in to parse your url to extract the #bookmark and then call the smooth scroll.