I'm using prototype to construct an ajax request from an inline onclick on a link. The function shows an element on the page and this all works fine, except that the browser scroll bar resets to the top after every click of the link. This is bad b/c sometimes the content that I want to show is partially scrolled down the page and this makes it so the user cannot see it. I realize it's better to not include the onclick inline, but I have a situation where I dynamically create these links and then cache the html so it is faster this way. Is there any way to cancel this browser scroll reset using an inline onclick? This is what my code looks like:
example
function linkAjax(word){
if(!making_ajax_request){
making_ajax_request = true;
new Ajax.Request('/example/test',
{parameters:{data: word},
onLoading: function(){searchLoading();},
onComplete: function(){
making_ajax_request = false;
}
});
} else { }
}
Your onclick needs to return false to stop the browser from reloading the page (resulting in scrolling to the top). Try:
example
Do this:
onclick="linkAjax('example') return false"
Related
A long content sub-page has multiple "read more" buttons done with jquery toggleClass.
When a user click the "read more" button the content is showing and the page gets refreshed. (I need the page-refresh for various reasons).
When the page gets refreshed, of course the content is not unfold anymore.
What I am trying todo is:
Save all unfold / fold toggle content before the page-refresh.
Go to the same scroll position before the page-refresh.
I am not sure what is the best way to keep the information -> Cookies, sessionStorage or localStorage for my case, because the user will usually open more sub-pages with "read more" buttons.
I made a JSFiddle (page refresh is not working on a fiddle).
I'd advise using sessionStorage for this.
First, remove all onclick=refreshPage() from your HTML. You want to keep all JS code inside your JS, and to set all handlers at one place. As a best practice, do not use onclick at all.
Next, create two functions: loadState() and saveState(). You will need to call call loadState() on every page load (refresh), and saveState() everytime a toggle button is clicked.
In your handler for clicks on button, also perform the page refresh.
The entire JS code:
$(window).on('load', function() {
loadState();
});
$('.read-more-toggle').on('click', function() {
$(this).next('.read-more-content').toggleClass('hide');
saveState();
refreshPage();
});
// Fold or unfold each content based on state before refresh
// And go to same scroll position before refresh
function loadState() {
let hidden_states = sessionStorage.getItem('hidden-states');
if (!hidden_states) {
return;
}
hidden_states = hidden_states.split(',');
$('.read-more-content').each(function(i, elem) {
if (hidden_states[i] === 'hide') {
elem.classList.add('hide');
}
else {
elem.classList.remove('hide');
}
});
document.scrollingElement.scrollLeft = sessionStorage.getItem('scroll-x');
document.scrollingElement.scrollTop = sessionStorage.getItem('scroll-y');
}
// Remember fold & unfold states, and scroll positions
function saveState() {
let hidden_states = [];
$('.read-more-content').each(function(i, elem) {
hidden_states.push(elem.classList.contains('hide') ? 'hide' : 'show');
});
sessionStorage.setItem('hidden-states', hidden_states);
sessionStorage.setItem('scroll-x', document.scrollingElement.scrollLeft);
sessionStorage.setItem('scroll-y', document.scrollingElement.scrollTop);
}
function refreshPage() {
window.location.reload();
}
Note: If at all possible, try to avoid a page refresh. Storing view states then recreating them after a refresh feels sub-optimal. In some browsers, it may also result in occasional scroll jump glitches as it repaints the restored states.
Lastly, consider if you really need jQuery for your project. Most functionality can be implemented in vanilla JS.
I would like to prevent the user to access subpages of my jqm page. To do that I use the pagebeforecreate event to check a certain condition and depending on that, change the page displayed (cancel current pageload and redirect or normally load the current starting/main page). The Problem is, that I still see the page flickering up before the changePage() is executed even when I call the preventDefault() method. I also used a relative URL as the first parameter (to = 'page.php') of the changePage(to, options) and since my #subpage1 lies within the page.php it should open - which it did - but then the transitions are broken because no real refresh was done.
Note that I have a page.php including different #subpage's (such as #subpage1, #subpage2).
jQuery(document).on('pagebeforecreate', '#subpage2', function(event, data) {
if (!isCondition1() && !isCondition2()) {
// stop loading #subpage2
event.preventDefault();
jQuery.mobile.changePage(jQuery('#subpage1'), {
data: 'lang=de¶m1=foo¶m2=bar',
reloadPage: true,
type: 'get'
});
}
// go on loading #subpage2
});
jQuery(document).one('pageinit', '#subpage2', function() {
// do something
});
Have you tried setting the body style to display:none in the html? And then if the page loads correctly you can set it's display property? That should be a 'workaround' to prevent the flicker of the page?
I'm designing an HTML page which has one button. The user clicks the button and a simple jQuery script animates that div away, revealing lower page content. You can see it here.
I've noticed that it looks/works fine the first time, but if I refresh the page with the browser button, it doesn't fully reset. The initial container is only half on the page. If I enter the URL again and load the page, it resets as expected.
NOTE: This only happens if you scroll down a bit after clicking the initial button... which seems weird.
I had no idea that there was any difference between these two operations, but there clearly is. What is the difference and how can I fix this problem from happening?
Here's my jQuery code, in case it's relevant:
$(document).ready(function(){
var faqs = $("#FAQ");
$("#learnmore").click(
function(){
$("#home").animate({top:'-=1066px'},600);
$("#more").animate({top:'-=1066px'}, 600, function() {$("#background").hide();} );
$("body").css('overflow-y', 'scroll');
//$("#home").slideUp();
console.log("jquery loaded");
}
);
});
It happens because it is cached by the browser.
If you styles are regularly modiefied, then as easy fix is to attach a unique id on the end of the reference, like
<link href="style.css?time=168768234928" ..../>
What it does, it makes the browser think it is a new request everytime it loads.
It happens because browser trying to scroll to the same position, what was before page reload. To check it, try press button and don't scroll to bottom of page and then reload page.
Okey, the reason is clear.
Now we need solution. Try this:
#more {display:none}
in your css. And then use
$("#more").show().animate(...
in your $("#learnmore").click() function. I hope this will solve the problem.
I have a button on the site I am working on that uses a sprite sheet animation and so needs to be set as a background image. I require a regular click on the button to delay the redirect to another page by a fraction of a second for the animation to play, however I still wish for middle mouse clicks to function to open in new tab, without a delay.
Currently I have this working in Javascript but it seems a pretty bad idea for everything to be handled that way and not to just have a href.
So I have made this:
<script type="text/javascript">
function delayed(){
window.stop();
setTimeout('window.location = "http://www.dog.com";', 800);}
</script>
I am a link
The idea being that a regular click triggers the function and incurs a delay whereas a middle mouse click will just go straight to the href link.
This works in Firefox. However in Chrome and Safari the middle click triggers the function and as a result opens the dog link in the same window (on the finished version the links will be the same of course).
Basically all I need is a href that delays on click but still functions normally on middle click. My working solution uses Javascript to open in new tab on middle click but it strikes me that this may override browser settings and is probably a bad idea.
EDIT:
In the meantime I had found this solution using Jquery:
$(document).ready(function() {
$(".delayed").click(function() {
var href = $(this).attr('href');
setTimeout(function() {window.location = href}, 800);
return false;
});
});
...and the HTML:
<a href="http://www.google.com/" class='delayed'></a>
This worked but encountered the same problem with Chrome treating a middle click as a left click and hence opening it in the same window.
I have now modified it to include the content from sransara so that... I think... everything is resolved. Again using Jquery:
$(document).ready(function() {
$(".delayed").click(function(event) {
var href = $(this).attr('href');
if(event.button == 0){
event.preventDefault ? event.preventDefault():event.returnValue = false;
setTimeout(function() {window.location = href}, 800);
}
});
});
Seems to work in all browsers. Hopefully these can be of use to anyone stumbling upon this page in the future.
This is just a quick solution, but I think it mostly fits into your need.
The code of HTML anchor tag:
I am a link
Here is the Javascript:
function delayed(event){
window.stop();
if(event.button == 0){
event.preventDefault ? event.preventDefault():event.returnValue = false;
setTimeout(function(){ window.location = "http://www.yahoo.com"; }, 800);
}
}
There are few simple changes:
I have removed the return false from onclick event, but the new code line event.preventDefault ? event.preventDefault():event.returnValue = false;, prevents default action when left clicked.
And added a button code check to Javascript.
Working demo code is here.
This is a quick solution, some area for improvement is to:
Take out the inline onclick event and add an event listener dynamically with JS.
Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the hashchange event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.
What I ended up doing was creating an object as such:
var pageload = {
ignorehashchange: false,
loadUrl: function(){
if (pageload.ignorehashchange == false){
//code to parse window.location.hash and load content
};
}
};
Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:
window.addEventListener("hashchange", pageload.loadUrl, false);
Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:
pageload.ignorehashchange = true;
and then the following line after each hash modification line:
setTimeout(function(){pageload.ignorehashchange = false;}, 100);
So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.
Check out history.js. There is a html 5 statechange event and you can listen to it.
onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.
Did you took a look at this? http://developer.yahoo.com/yui/history/