How to prevent scrolling to the top after unhiding/hiding text? - javascript

There is an old StackOverflow question on how to unhide/hide text using +/- symbols.
Cheeso posted a nice solution with some sample code. It was just what I was looking for, although the original poster didn't agree. :-)
I'm using the code on a web site that is intended to be used on mobile devices. The only problem is that the page jumps back to the top of the screen whenever the +/- is tapped.
Is there anyway to get around that? Thanks.

In your click event handler, return false.
$('a.selector').click(function() {
return false;
});

Here is the answer that Cheeso provided to me in email. I am posting it here for the benefit of others who follow. This didn't quite work and I am in the process of figuring out why.
If you change this line
$('div p a[href="#"]').click(function() { expando(this); });
to this:
$('div p a[href="#"]').click(function(ev) { ev.preventDefault(); expando(this); });
...I think it should stop scrolling to the top.
When a user clicks on a link that has a hash character, the browser is expected to scroll to the location on the page where the fragment marker is placed. Like a bookmark. For example, in this URL: http://en.wikipedia.org/wiki/Causes_of_WWII#Militarism The fragment (bookmark) is #Militarism , and if you click that link, your browser will scroll to that section.
In the case of that sample I wrote, the hrefs are bare # characters, which implies an empty fragment. And I suppose the browser is scrolling to the default location, which (I guess) is "the top of the page".
To avoid this, just call ev.preventDefault() in the click handler. This is a jQuery trick that suppresses the normal handling of the click; in your case, it suppresses the part where the browser tries to scroll to a non-existent anchor.

Implement event.preventDefault() in the click handler.
$('a').click(function(e) {
e.preventDefault();
// more code here
});

Related

Make browser's back button work when using hide and show (jquery)

I've seen the new website of megaupload (mega) and we've got this:
Ok, if I press on left-menu contacts, it only reloads the white part on the image, if I press messages, the same, it only reloads white part. But if I go from contacts to messages and I press browser's back button, it goes from messages to contact and only reloads white part as always.
In my website, I do the same using jquery hide and show, but obviously, if I press browser's back button it doesn't hide the div and shows the other one.
My web site is only one html file and there are 4 div that get shown or hidden depending on the button you press, this is an example:
$("#btn_contact").click(function () {
$("#content_contact").show();
$("#content_home").hide();
$("#content_products").hide();
$("#body_aux").hide() ;
$(this).addClass('visited');
$('#btn_products').removeClass('visited');
$('#btn_home').removeClass('visited');
});
Can anybody tell me how to find this with jquery or whatever I have to use.
I don't know if I've explained myself well, if not, ask me to do it better.
I would appreciate any help. Thanxs a lot.
Maybe it'd be easier for you and more appropiate to make "content_contact.html", "content_home.html", and so on and use .load() function as Ozan Deniz said. You wouldn't have to change margins, positions, etc. and back button would work withouth programming. I think is not appropiate to make the whole website using just one html file, showing and hiding div's, ofcourse you can do this but maybe is not the right way. I'm newbie at this, but that's what an expert told me beacuse I was doing something similar to that.
Hope to help you.
You can use jquery load function to load white part
For example;
$('#result').load('ajax/test.html');
And in back button event you can load the white part
jquery hide and show
window.onbeforeunload = function() { $('#result').hide(); }; or
window.onbeforeunload = function() { $('#result').show(); };
jquery load function
window.onbeforeunload = function() { $('#result').load('ajax/test.html'); };

How to get Ajax links marked as "visited" without messing up IE9

I have a page full of links that each AJAX in an article based off an ID. I'm trying to use history.pushstate to mark articles as "visited".
What I've done:
I added a hash to each link with the ID of the article:
Title
Inside my JS function I have something like:
if (window.history && window.history.pushState)
{
window.history.pushState({articleID:"123"}, "Title", "#ID=123");
}
The value inside my href is not used in anyway, I just put it there so that the links would get "visited" CSS. This works well in most browser except of course IE9. Since IE9 does not support window.history, I never expected it to work.
However, my problem is that clicking articles in IE changes the URL to append the hashes on them and this pollutes the history (now have to click back a whole bunch of times to go back).
I know that I could get rid of the hashes and still have back button work (outside of IE), but I'm actually more interested in making sure my links get marked as "visited". Is there anyway to get ajaxy links marked as "visited" without having IE9 behavior compromised?
Try adding this to your onclick handler:
if (event.preventDefault) event.preventDefault(); else event.returnValue = false;
Simply return false; from your onclick handler.

Can't alert href val?

The following code gives me an alert with nothing but a # symbol inside it. Why?
EDIT: I should note that the code is inside a jQuery .click event...if I place it outside of that, it works properly. Here is the fuller code:
$('#continue').click(function(){
var _href = $("#continue").attr("href");
alert(_href);
});
Continue
EDIT2: This all works fine in jsfiddle. But in the xcode iphone simulator I just get #.
Judging by only the code you typed, probably the code runs too early. Try wrapping the JS in
$(function() {
// your code here
});
Or
$(document).ready(function(){
// your code here
});
Update:
Well, since it's an iPhone simulator, it changes things. Remember, nobody can help you unless you give all the details of the problem, no matter how much experience they have.
Did you try the touchstart / touchend / tap events instead of click? As far as I know, Apple has been having problems with the click events. Also, click events on mobile devices will have a slower response (a delay of approx 300ms if I remember well) so you're better just using touch specific events.
What are you building? Is it a mobile web app or? Will it run in a standard mobile browser or something like PhoneGap etc?
Update2:
Ok. It works as long as the code is not called on Click. This eliminates the possibility of another piece of code replacing your "href" with another value because that code would have to be inside your $('#continue').click(function(){ }); block.
The click event is simulated on a touch phone, that's why the touch events are faster (they are native) and less likely to cause problems. You should also make sure that you return false there and not follow the link, that might be what's replacing your "href".
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#continue').click(function(e) {
var _href = $(this).attr('href');
alert(_href);
e.preventDefault();
return(false);
/*
the return is legacy code, used by some
browsers to detect if current event handler
is braking default behaviour
the e.preventDefault() function is the jQuery
way to do it
*/
});
});
</script>
Continue
Without this line the link is followed and a refresh occurs killing the current script.
https://github.com/jquery/jquery-mobile/issues/3777

iPad webapp problems: statusbar over page, html/JS links

I have a webpage/webapp that works really good. Just 2 problems right now:
The statusbar of the iPad is not above the page, like i think it should be, but its in the page. So the top ~10px are overlayed by the statusbar and therefore my menu at this place is nearly unusable. I used 'black-transulent' but also 'black' as statusbar-styles.
Html links are leaving the webapp-mode. Well known problem. I found a solution which seems to come from the iWebKit:
var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
{
a[i].onclick=function()
{
window.location=this.getAttribute("href");
return false
}
But this overrides the click events from Javascript links that i have in my code. Is it possible to check if the click event is already set? JQuery allowed. If i check for $('ImAButton').click it always returns function.
If I understand your problem can you not call preventDefaults in the javascript event handler?

HTML anchor link with no scroll or jump

I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.
Simulated sample code:
button 1
button 2
Home
So if you were to click on the "button 1" link, the url could be http://example.com/foo.php#button1
Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.
The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an onclick handler and return false. Even just adding it as an attribute should work:
button 1
A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the window.location.hash variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like window.location.hash = this.id though I'm not sure how mootools handles events.
(Also you need all of the IDs to be unique)
You can use the code below to avoid scrolling:
linktxt
I'm probably missing something, but why not just give them different IDs?
button 1
button 2
Home
Or whatever convention you'd prefer.
Also, preventDefault
$(your-selector).click(function (event) {
event.preventDefault();
//rest of your code here
}
I found the solution. Here I save an old location from calling href
and restore it after scrolling
<script language="JavaScript" type="text/javascript">
<!--
function keepLocation(oldOffset) {
if (window.pageYOffset!= null){
st=oldOffset;
}
if (document.body.scrollWidth!= null){
st=oldOffset;
}
setTimeout('window.scrollTo(0,st)',10);
}
//-->
</script>
and in body of page
<a href="#tab1" onclick="keepLocation(window.pageYOffset);" >Item</a>
Thanks to sitepoint
An easier way would probably be to add it as a GET. That is, http://example.com/foo.php?q=#button1 instead of http://example.com/foo.php#button1
This won't have any effect on how the page is displayed (unless you want it to), and most scripting languages already have tools in place to easily (and safely) read the data.
Well here we are 7 years after this answer was published and I found a different way to make it work: just point the window.location.hash to a non-existent anchor! It doesn't work for <a>s but works perfectly in <div>s.
<div onclick="window.location.hash = '#NonExistentAnchor';">button 1</div>
Worked fine in Chrome 56, Firefox 52 and Edge (IE?) 38. Another good point is that this doesn't produce any console errors or warnings.
Hope it helps somebody besides me.
There is a solution without any JavaScript at all:
I will not jump to the top
Use
button 1
where
function setHash(hash) {
event.preventDefault();
history.pushState(null, null, "#"+hash);
}
event.preventDefault() stops browser from what it normally would do on clicking, and history.pushState adds to the sessions history stack.
For further discussion, see here and here

Categories

Resources