Prevent page from going to the top when clicking a link - html

How can I prevent the page from "jumping up" each time I click a link? E.g I have a link somewhere in the middle of the page and when I click it the page jumps up to the top.

Is the anchor href="#"? You can set it to href="javascript:void(0);" instead.
If you are going to a prevent default please use this one instead:
event.preventDefault ? event.preventDefault() : event.returnValue = false;

Let's presume that this is your HTML for the link:
Some link goes somewhere...
If you're using jQuery, try like this:
$(document).ready(function() {
$('a#some_id').click(function(e) {
e.preventDefault();
return false;
});
});
Demo on: http://jsfiddle.net/V7thw/
If you're not on jQuery drugs, try with this pure DOM JavaScript:
window.onload = function() {
if(document.readyState === 'complete') {
document.getElementById('some_id').onclick = function(e) {
e.preventDefault();
return false;
};
}
};

It will jump to the top if you set the link href property to # since it is looking for an anchor tag. Just leave off the href property and it won't go anywhere but it also won't look like a link anymore (and make sure to handle the click even in javascript or else it really won't be of much use).
The other option is to handle the click in javascript and inside your event handler, cancel the default action and return false.
e.preventDefault();
return false;

Related

Disabled button is clickable on Edge browser

I have problem with Edge browser. In my web site I have buttons with span tags inside them. In this span tags I bind text and icons. So far I had no problem but on Edge browser it is possible to click on disabled buttons. After investigating problem I found out that, when button contains span tags inside, it is possible to click on button. Here is how it looks on my web site:
<button id="btnRefresh" type="button" class="btn btn-primary" ng-click="refresh()" ng-disabled="performingAction">
<span ng-class="performingAction && action == 'refresh' ? 'fa fa-cog fa-spin' :'fa fa-refresh'"></span>
<span>{{ refresh }}</span>
</button>
Here is example to testing:
<button type="button" disabled="disabled" onclick='alert("test");'>
<span>Click me!</span>
</button>
One option would be to hide buttons instead of disabling, but I prefer to disable them. Please suggest solution to over come this issue.
Just set
pointer-events: none;
for disabled buttons.
Here's CSS to disable all disabled elements everywhere:
*[disabled] {
pointer-events: none !important;
}
pointer-events documentation
This is a bug in Microsoft Edge. Disabled buttons accept clicks if they contain any HTML elements (i.e. if they contain anything else than just text).
Reported multiple times via Microsoft Connect:
Event bubbles from child element into element (by SO user Ryan Joy)
Bootstrap/Jquery disabled buttons generate click events and show tooltips even disabled
The bug was still present in Build 10565 (16 October 2015).
It was fixed in the November update, Build 10586.
A possible (but ugly) workaround is to call some Javascript in onclick for every button, which then checks if the button is disabled and returns false (thus suppressing the click event).
One work around I've come up with using angularjs is inspired by Ben Nadel's blog here
So for example:
angular.module('myModule').directive(
"span",
function spanDirective() {
return ({
link: function (scope, element, attributes) {
element.bind('click', function (e) {
if (e.target.parentNode.parentNode.disabled || e.target.parentNode.disabled) {
e.stopPropagation();
}
})
},
restrict: "E",
});
}
);
Since you're not always going to be using a span element and probably don't want to create a new directive for every element type, a more general workaround would be to decorate the ngClick directive to prevent the event from reaching the real ngClick's internal event handler when the event is fired on a disabled element.
var yourAppModule = angular.module('myApp');
// ...
yourAppModule.config(['$provide', function($provide) {
$provide.decorator('ngClickDirective', ['$delegate', '$window', function($delegate, $window) {
var isEdge = /windows.+edge\//i.test($window.navigator.userAgent);
if (isEdge) {
var directiveConfig = $delegate[0];
var originalCompileFn = directiveConfig.compile;
directiveConfig.compile = function() {
var origLinkFn = originalCompileFn.apply(directiveConfig, arguments);
// Register a click event handler that will execute before the one the original link
// function registers so we can stop the event.
return function linkFn(scope, element) {
element.on('click', function(event) {
if (event.currentTarget && event.currentTarget.disabled) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
});
return origLinkFn.apply(null, arguments);
};
};
}
return $delegate;
}]);
}]);

Trying to put Bootstrap modal in a button

Is there a way I can use a button(input type="button") to show the Bootstrap modal. Basically the default is using anchor based on the documentation. I have tried experimenting but no luck.
I'm not sure if my coding is wrong or the Bootstrap modal can only be activated if it is an anchor tag. I have also tried googling or researching if anyone has created this kind of result.
This should work the same way as with an anchor tag.
The problem is, it's based on the href attribute, referring to the id of the modal window, and placing this attribute on a button might cause some html validation to go wonky.
If you don't care about that kind of stuff you can just replace your a tag with a button tag.
Edit: just noticed you were using an input element rather than a button. Either way, it should still work.
Edit2: Just verified if what I was saying wasn't total BS by looking at the bootstrap code (2.3.2), and found this snippet:
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
Looking at this, the href attribute isn't required, and you can use data-target instead when working with inputs and buttons.
simply u can fire event on Button Click and call function "onclick=showModal()"
JS CODE
function showModal()
{
$("#modal-window-id").modal("show");
}

Keep URL unaffected when anchor link is clicked

I've checked other posts on here, no results of what I'm looking for.
I want to click on
About
<div id="about">Content of this..</div>
and have it scroll to that element without putting www.domain.com/#about in the address bar
As a perfect example please check out this site that I found here and click on some of the links --they don't change the address bar when clicked.
You can do what you want using javascript and jquery, example below (note that this is using an old version of jquery):
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1200);
});
});
</script>
</head>
<body>
<a class="scroll" href="#codeword">Blue Words</a>
<div id="codeword"></div>
</body>
</html>
Played around with this myself and here is a summary of my learnings on the subject.
Here's the basic link command:
Blue Words
Here's how you denote where the jump will scroll the page:
<A NAME="codeword">
Here's what's happening
The A HREF command is the same as a basic link except the link is to a codeword rather than a URL.
PLEASE NOTICE there is a # sign in front of the codeword. You need that to denote it is an internal link. Without the # sign, the browser looks for something outside the page named after your codeword.
Your "codeword" can be just about anything you want. I try my best to keep it short and make it denote what it is jumping to. There might be a limit to the number of letters you can use--but I haven't found it yet.
The point where the page will jump follows the same general format except you will replace the word HREF with the word NAME.
PLEASE NOTICE there is no # sign in the NAME command.
Note! Where you place the NAME target will appear at the top of the screen browser.
Hope it helps.
window.location.hash = ""
is the possible way I could find.
hash gives the string next to #.
//dont use a, use class
$(document).ready(function(){
$(".mouse").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes
to scroll to the specified area
$('html, body').animate({
scrollTop: $("#section").offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = "";
});
} // End if }); });
One possible workaround is to use a <button> instead of a <a>.
So rather than....
About
<div id="about">Content of this..</div>
...you can change it to
<button href="#about">About</button>
<div id="about">Content of this..</div>
This way the anchor link will not affect the URL.
For me, only inserting "return false;" solved this issue.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" async></script>
<script>
jQuery(document).ready(function($) {
$('a[href^=#]:not(a[href=#])').click(function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top}, 1300, 'easeInOutExpo');
return false;
});
});
</script>
(This applies to all anchor links on the page.)
I tried to monitor window.location.hash using a MutationObserver, but that doesn't work, see How to use (or is it possible) MutationObserver to monitor window.location.pathname change?
So now I'm using the window.onpopstate() eventListener:
var flag_onpopstate=false; // use this global flag to prevent recursion
window.onpopstate = () => {
if (flag_onpopstate) return;
flag_onpopstate = true;
window.location.hash = "";
flag_onpopstate = false;
}
A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.

a link should not show # in URL and scroll up when its href="#"

How can I make a link a href="#" does not show # in URL when clicked and does not scroll up the page?
I have seen it in http://www.offroadstudios.com/creative-agency
But could not learn how they did it.
Left menu contains a href="#" but it behaves in the way I am asking.
Looking at that site it would appear they are using jQuery to change the visible content. To prevent a # from appearing in your browser bar, you can preventDefault:
$("a.myLinkClass").click(function(e){
e.preventDefault();
//do something..
});
See Demo: http://jsfiddle.net/SJuwL/show
In topic author link, they used this:
jQuery(document).ready(function() {
jQuery('.product-selector').each(function(i, element) {
jQuery('.product-selector.product-' + i).click(function() {
jQuery('a#products-top').focus();
if (producttool == false) {
producttool = true;
}
// Return false so that the page doesn't switch.
return false;
});
});
});
So, the answer on your question, is to return false; in onclick event.
Demo here: http://jsfiddle.net/FSou1/K3p2W/
$('a[href="#"]').click(function(event){
event.preventDefault();
});
Attack a click handler to the link and prevent the default action
$('a').click(function(){return false});
http://jsfiddle.net/MjyzK/show/
To link-jump to a position in the HTML file it is possible to use a named anchor tag.
<a name="here"></a>
LINK <!-- jumps to the position "here" -->

jQuery Radio Button Image Swap

I am essentially brand new to coding (html5 forms, CSS3 and now jQuery).
What I am trying to do is have an imageswap (which I have done) attached to a radio button. So what I'm doing is replacing the buttons with images, each with a "pressed" version. However, before even attaching it to a form function/radio button input, I want to find a way so that when I click one button, it switches the other images back to "un-pressed". Essentially so that only one image can be "pressed" at a time.
Right now the code for me pressed images are
$(function() {
$(".img-swap1").live('click', function() {
if ($(this).attr("class") == "img-swap1") {
this.src = this.src.replace("_U", "_C");
} else {
this.src = this.src.replace("_C","_U");
}
$(this).toggleClass("on");
});
});
I thought about using an if statement to revert all the "_C" (clicked) back to "_U" (unclicked).
Hopefully I've included enough information.
A good pattern for solving this problem is to apply the unclicked state to ALL your elements, then immediately afterward apply the clicked state to the targeted element.
Also, your if statement ($(this).attr("class") == "img-swap1") is redundant -- it will always be true because it's the same as the original selector $(".img-swap1").live('click'...
Try
$(function() {
$(".img-swap1").live('click', function() {
$(".img-swap1").removeClass('on').each(function(){
this.src = this.src.replace("_U", "_C");
});
this.src = this.src.replace("_C","_U");
$(this).addClass("on");
});
});
If I understand the question correctly the following may work for you:
$(function(){
$('.img-swap1').live('click', function() {
$('.img-swap1').removeClass('on').each(function(){
$(this).attr('src', $(this).attr('src').replace("_C", "_U")); // reset all radios
});
$(this).attr('src', $(this).attr('scr').replace("_U", "_C")); // display pressed version for clicked radio
$(this).toggleClass("on");
});
});
I hope this helps.