Page moves on link submit - html

I was wondering if anyone knew how, when on link submit the page does not move i.e
If it was 2 page lengths down it would shoot up to the top.

If you have attached event to HTML control through jQuery then you can use return false like
$("#myDiv").delegate("tr", "click", function() {
enter code here
return false;
});

No need to replace anchors, as your own answer to the question states.
This will work just as well:
<a href="#" onclick="yourOwnSubmitFunction(); return false;">
In short, just make sure that whatever function is in the onClick handler returns boolean false.

Whilst having the link's onclick handler return false; is the correct way to stop a link being followed, it's a bit of a hack to use a link this way, because what you've got is an action and not a link. You can't do the usual link-like things to your link, like right-click-bookmark, or middle-click-for-new-tab and so on, so it shouldn't really have that affordance.
An alternative (that eg. SO uses) is to put the onclick on a non-link element instead, eg.:
<span id="potato">Do something</span>
<script type="text/javascript">
document.getElementById('potato').onclick= function() {
// do something
};
</script>
This is cleaner, but has a drawback in is that the link can't be focused and activated by the usual keyboard tabbing method.
Arguably better is to use an <input type="button"> or <button type="button">, which are the right markup to represent an action. Of course these look quite different, but you can use CSS to style them so that they look like a link instead of a button if you like. The one drawback of this method is that good old silly IE cannot completely restyle a button; you will get a few pixels of unremovable extra padding in this browser.

If you are using .net 2.0
There is a
MaintainScrollPositionOnPostback
property in #page directive that you can use to maintain the scroll position of the page.
Gets or sets a value indicating
whether to return the user to the same
position in the client browser after
postback. This property replaces the
obsolete SmartNavigation property.
When Web pages are posted back to the
server, the user is returned to the
top of the page. On long Web pages,
this means that the user has to scroll
the page back to the last position on
the page.
When the
MaintainScrollPositionOnPostback()()()
property is set to true, the user is
instead returned to the last position
on the page.
If you can't use this then set location.href to an anchor tag at the specified position after the submit.
location.href = "#anchAtPos";
where anchAtPos is the id of the anchor tag at a specified position.

I solved this using:
function anchorReplace()
{
$("#reportWrapper a").each(function(i){
var anchorElement = $(this);
var newAnchorElement = $('<a href="#link' + i + '" name="#link' + i + '">'
+ anchorElement.text() + '</a>').insertBefore(anchorElement);
anchorElement.remove();
});
}

I've fixed this before by putting
onclick='return false;'
Inside the link
<a href="#" onclick='return false;' id='attachAlistenertothisID'>This link doesn't jump to the top!</a>
I use this for my links that have click listeners attached them via jQuery.
Hope this helps someone!

Related

How to refresh a page and load at top after an anchor has been clicked, ignoring the anchor, and resetting back to the top?

I have a page with a few anchors. When a user clicks an anchor, the anchors work, and user is taken to the correct location.
If a user tries to refresh the page, it retains the anchor ID in the URL window and so naturally, when refreshing, it does not go back to the top of the page.
I think it would be more user friendly to go back to the top of the page on a refresh.
How would I achieve this?
My page currently is primarily using bootstrap, css, jquery, javascript, and php.
I think I need to set up some code so that after clicking the anchor, it removes the anchor from the url window, so that if someone refreshes, they'd be refreshing just the initial page state without an anchor, but I don't know how to begin. Or maybe I'm over thinking this and there's some way to always go to top of page on a refresh regardless of anchors or not. I'm not too code savvy.
Right now my code is like this...
An example of one of my anchors:
<a class="hoverlink" href="#firefighter"><li style="float:left; margin-right:1em; color:white; background-color:red" class="appao-btn nav-btn">Fire Fighter</li></a>
One of the elements for example that the anchor will jump to:
<div style="min-height:10px;" name="firefighter" id="firefighter" class="anchor"><p style="min-height: 10px;"> </p></div>
CSS style on my anchors:
.anchor:target { height:200px; display: block; margin-top:-2em; visibility: hidden;}
Actual Results With My Code: Page Refresh Stays At Anchor Location
Desired Results: Page Refresh Goes To Top Of Page
After some searching, I found a solution that almost works for me:
<script>
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
</script>
But it creates a flickering effect that doesn't look the best such as my example site at
https://graceindustries.com/gracetest/Grace%20Industries%20Website%20Design%202019%20Alternate%20Version/documentation.html
Anyone know how to remove the "flicker"?
You can try this (with the .some-anchor is the class for all a tag that points to some destinations within the page).
$('.some-anchor').click(function() {
var target = $(this).attr("href");
$('html, body').animate({
scrollTop: $("" + target).offset().top
}, 1000);
return false;
});
The "return false;" or preventDefault() event method will prevent the page from flickering. As I observed this does not make the # to the URL so refreshing is not a problem.
Other helpful answer: jQuery flicker when using animate-scrollTo
Navigating to page content using URL Fragments (#someLink) in anchor tags is a core part of the HTML specification. The standard implementation in most (if not all) web browsers is to add the fragment to the address bar. The fragment is part of the URL and therefore, when the page is refreshed the browser scrolls to the element with that ID. Most users will be familiar with this behaviour, even if they don't understand how or why it works like that. For this reason, I'd recommend not working around this behaviour.
However, if it is absolutely necessary, the only way to achieve the result you're looking for is to not use URL fragments for navigation and use JavaScript instead, therefore not putting the fragment in the URL in the first place. It looks like the Element.scrollIntoView() method might do what you're looking for. Rather than having
Click me
you'd use
<a onclick="document.getElementById('element1').scrollIntoView();">Click me</a>
or even better, implement this in an external JS file. If you experience issues due to the element not having the href attribute, you could always add an empty fragment href="#".
You can remove the id from the url right after the user click on the anchor tag
history.scrollRestoration = "manual" will set the scroll to the top of the page on refresh
<a onclick="removeAnchorFormURL()" href="#sec-2">here</a>
<script>
history.scrollRestoration = "manual";
const removeAnchorFormURL = () => {
setTimeout(() => {
window.history.replaceState({}, "", window.location.href.split("#")[0]);
}, 100);
};
</script>
window.location docs
location.href docs
location.replace docs
scrollRestoration docs (check it for info on scrollRestoration compatibility)

AngularJS closing a div which shows up on ng-click

I created a button
<button type="button" ng-click="chooseOptions()" id="chooseOptionButton" ng-bind="whatToDisplay()"></button>
Which shows a <div ng-show=appearOnChoice>on click and toggles back when clicking again!
$scope.chooseOptions=function(){
$scope.appearOnChoice=!$scope.appearOnChoice;
}
However, I also want this element to hide again, when the user clicks anywhere outside this div
element. How can I do this? I need strictly stick with AngularJS and not use jQuery.
Hope you can help me with that.
EDIT: I tried to adapt some of the events of bootstrap datepicker, but I am not sure how to apply it properly
$scope.$on('datepicker.focus', focusElement);
scope.$watch('isOpen', function(value) {
if (value) {
scope.$broadcast('datepicker.focus');
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
$document.bind('click', documentClickBind);
} else {
$document.unbind('click', documentClickBind);
}
});
var focusElement = function() {
$timeout(function() {
self.element[0].focus();
}, 0 , false);
};
How can I adapt this to my case?!
I think that you dont have to write a function, you can use ng-init to create a model, ng-show to show/hide the div based on the value of the model, and with ng-click change the value of the model. See example below:
var myapp = angular.module('myapp',[]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-init="showDiv = true;" >
<div ng-show="showDiv"> SHOOOOOOOOW </div>
<button ng-click="showDiv = !showDiv;">Click me</button>
</div>
</div>
You can set the model value to be false when the user is clicking everywhere else, and set it again to true when it clicks the button. If you made a fiddle I can help you easier :)
If the DIV has focus, then you can use the ng-blur directive on the DIV to run set appearOnChoice to false. However, if the DIV does not already have focus (which it won't if you are depending on the button to make it visible), you will need to manipulate the DOM in your code (to provide focus) OR create a custom directive to set focus so that the ng-blur directive will work. Check out possibilities for that with this link.
alternatively, you can add an ng-click directive to every clickable object on your view that will hide the DIV when fired. But I don't really think that's the best way to go...
The easiest and cleanest way to handle the click away is to register and event on the document that will remove the element when anything other than it, or its children, are clicked.
For an example of a service that does this see GitHub EnzeyNet/Services
Sorry about the lack of documentation there but after injecting the service you would use it like this.
var divElem
nzService.registerClickAwayAction(function() {
divElem.remove();
}, divElem);
I simply solved it by using a ui bootstrap dropdown. This comes along with an is-open option and closes on click outside.

Remove Anchor URL Label

I wonder if someone can guide me on how to remove the url label that appears at the bottom of the page when you hover over an anchor (I wonder if it's even posible). I've googled a lot and didn't find any answers.
Suppose I have
<a href="www.somepage.com" title="The Page">Link< /a>
in the bottom of the page there will appear a tooltip/label showing "www.somepage.com".
Please see here for an example
Thanks in advance!
You can use either Javascript or JQuery.
For example, you can set to A attribute "href=#" and add an attribute url=www.somepage.com something like this:
Link
If you click over this nothing happen.
Now, you need to apply with javascript or JQuery click event. The next example is using JQuery and Javascript:
At the bottom of page's body:
<script>
$('#link').click(function() {
var url = $(this).attr('url');
window.location.href=url;
});
</script>

TabIndex - hitting tab moves me to Address Bar - unable to work around this using Focus or +tab indexes

I read several threads that talk about how the Address Bar in IE is basically the first one to get focus when using TAB (MSDN's own docs talk about this).
Yet, I have seen situations where this doesn't always have to be the case....
I have a master page and inside my content area is a formView.
It defaults to INSERT view and can never leave it (they can only insert not edit and reading is handled elsewhere)
So on my page load for the page I have:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If fvwLogEntry.CurrentMode = FormViewMode.Insert = True Then
'Set the default field to position the cursor there...hopefully
Dim FCtxtHrEmployeeId As TextBox
FCtxtHrEmployeeId = CType(fvwLogEntry.FindControl("txtHrEmployeeId"), TextBox)
Page.SetFocus(FCtxtHrEmployeeId.ClientID.ToString)
End If
Now that works, when the page loads it sets the cursor to the employeeID text box inside the formview's INSERT template.
HOWEVER, when I hit TAB it takes me to the address bar and THEN if I hit tab again it takes me through the rest of the items on the page.
I set the tab index of the first item to 11 and then incrimented from there (I had read that IE's toolbars have tab indexes too so I thought perhaps using a higher number would bypass those, but again that doesn't REALLY make sense since it would still start at the lowest number, but I gave it a shot thinking it would move forward from where the focus was set.) If I click on the textbox and then hit TAB it DOES move through the page like I would expect.
It is just when the page loads and gets the focus set to the employeeID textbox that hitting tab moves it to the address bar.
I also tried setting the other controls to -1 (those I didn't want it to tab to), still no luck there.
So... what can I do to get around this?
There MUST be a simple way to set the focus to the employeeID textbox and ensure that pressing TAB after that moves to the next control in the formview's insert template and does NOT jump up to the address bar?
The following jquery code seems to be working fine for me..
$(window).load(function () {
$('.myClass :visible:input:enabled:first').focus();
});
$('body').on('keydown', '.myClass :visible:input:enabled:first', function (e) {
if ((e.which == 9) || (e.keyCode == 9)) {
$('.myClass :visible:input:enabled:first').focus();
}
});
I found another better option which is fastest as of what I tried.
Here's the code for that
function handleTabOrder() {
$('.myClass :visible:input:enabled').each(function (index) {
$(this).attr('tabindex', index + 10);
});
$('.myClass :visible:input:enabled:first').keydown(function (e) {
if (e.keyCode == 9 || e.which == 9) {
$("[tabindex=10]").focus();
}
});
}
What I have done here is to assign Tab order to all the visible controls on the page, then I have handled the key down event of only first control(that shifts the control to address bar) and now it shifts the control to next visible input item on the screen..
Its just a work around but works faster than any of the other things mentioned in the thread.
Just write the above function and all it in on-load event of page.
I was having this issue as well. For me, it was being caused by the use of the .select() method in order to bring focus automatically on a text field as soon as the page loaded. I changed my code to instead use JQuery's .focus() method and that resolved the issue.
I faced similar problem in IE. After some analysis I found that, this problem occurs if there is any HTML content outside form.
for example:
<html>
<div id="1">
</div>
<form>
//other code
</form>
</html>
It worked for me, after I moved all HTML inside form tag.
<html>
<form>
<div id="1">
</div>
//other code
</form>
</html>
Have a look at: http://www.w3schools.com/tags/att_global_tabindex.asp
Your txtHrEmployeeId element should have tabindex 1 and all other elements should have higher values.
-1 is not valid
Also verify that the tabindex are correct in the html that gets rendered (right-click in page and "view source").
I realize this is an old post, but an even simpler method is to add a "tab-stop" attribute to the form element with the last tabindex. Then bind a keydown listener and force focus to the first tabindex when the tab-stop is encountered.
Here's a simple example:
<input type="text" tab-stop />
$document.bind("keydown", function(event) {
var attrs = event.currentTarget.activeElement.attributes;
if (attrs['tab-stop']) {
angular.element.find('select')[0].focus();
event.preventDefault();
}
});
};
The answer mentioned in my other post works fine but it made the page take a huge performance hit because with every key press on the page the whole DOM was being searched for the elements.
So I found a new more optimized solution
var myNameSpace = function(){
this.selector = '.myClass :visible:input:enabled:first';
this.myElement = $(selector);
this._body = $('body');
var _self= this;
this._body.on('keydown',_self.selector,function(e){
if ((e.which == 9) || (e.keyCode == 9)) {
_self.myElement.focus();
}
});
};
The general idea being to 'cache' the node to be accessed. No need to traverse the DOM again and again for just selecting.
I had this same problem. It turns out mine was related to the ajax modal popup extenders. a modal popup was being shown, even though technically i could not see it because it was wrapped inside a parent div that was hidden. if you are using modal popup extenders, this could be causing an issue like this.
If you are using JSF or Primefaces, you can make use of:
<p:focus for"formname"></p:focus>

html anchor tag onclick problems !

I came across a strange problem with html anchor tags. I have an anchor tag on the html page and on clicking the 'a' tag it is supposed to give me an alert message. It is working well. But, If I append a new 'a' tag using jquery to the html page and on click of that appended 'a' tag is not working. i was able to give href, target blah blah blah to the appending 'a' tag but.. onlick function is not working. Any thoughts ???
Thanks in advance.
In jQuery, you typically use the .click() function on a selector to set the click handler. Note that if multiple items match the selector, multiple items will have the click handler installed.
Here's a trivial code snippet that should do what you want:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function addLink(label, msg) {
/* Create link element.
The href="#" makes the link act like a link
(be highlighted, selectable, etc.).
The onClick="return false;" keeps the link from
scrolling the browser to the top of the page.
The onClick is not interfered with by jQuery's
.click() . */
var link = $('' + label + '');
/* Install click handler. */
function clicked_handler() {
alert(msg);
}
link.click(clicked_handler);
/* Add the link to the body. */
$('body').append(link);
}
addLink('Link 1', 'You clicked link 1');
$('body').append('<br/>');
addLink('Link 2', 'You clicked link 2');
</script>
</body>
</html>
Your question is unclear.
I assume that you're adding a click handler to the <a> tags by writing $('a.whatever').click(function() { ... }), then adding new <a> tags to the document.
When you write $(...).click(...), it only adds handlers to the elements that were found by the $(...) at the time you added the handler. It will not apply to any elements you add later.
You're probably looking for jQuery's live method, which will handle an event for all elements that match a selector, no matter when they were created.
For example:
$('a.whatever').live('click', function(e) { ... });
Try using this:
$("a").live("click", function(){
alert("Tadah!");
});
Adding an event works on stuff that is already on the page. If You add something aferwards You have to bind a new click eventto this new thing or use live, which always should be the second option
so instead of doing
$(something).append('<a href="" etc. ');
try something like this
$('<a></a>').attr('href','some url here').bind('click',function(){}).appendTo('body');