I don't want the browser to jump to an given id in :
Learning diagnosis
Few links direct to another page so i need the anchor tag. But in the same page i have written a code to scroll to a proper location.
I have tried:
e.preventDefault();
return false;
e.preventPropogation();
none of the above works.
Basically when on same page i want to override the default scrolling. I have written scrollTop but it doesn't work since the default scrolling take place
Try to find out # in attr of a tag:
$("a").on("click", function(e) {
var hasUrl = $(this).attr('href').split('#')[0];
alert(hasUrl == "")
if(hasUrl == "") {
return false;
} else {
alert('redirect');
}
})
Here is updated fiddle
Related
Has anyone of you came across a similar problem I have. I have links on one page of my website which redirect to the second page where I have a menu that is showing one menu option at a time. By default, the first option is visible when I open up the second page. But how can I get a result when I click on a link like this to show the hidden div and scroll down to the specific part of the divs content?
Link on the first page. It's supposed to load option 4 and scroll down to anchor #extrainformation.
<div class="linktosecondpage" onclick="window.open('http://localhost/mypage/secondpage#extrainformation','_self');">
</div>
How does the menu look on the second page?
https://jsfiddle.net/wmr03zno/3/
I have considered writing out a function to each link that activates when clicked on the link, redirects to the second page, shows the hidden option of the page, removes and adds class to h4, and scrolls down to desired anchor(#extrainformation). That's the idea I have right now. Just wondering if there is an easier workaround to this kind of problem.
My idea will be to read hash from link and if element with given hash exists scroll to it.
on first page you will have a link like:
anchor
and on second page you will need something like this:
when page ready state will be changed to interactive check if link contains anchor (location.hash) and if it contains try scrollToElement() function.
In function check if element with given anchor exist and if it does then show it and scroll to it.
const scrollToElement = (id) => {
const element = document.querySelector(id);
if (element !== null) {
element.classList.remove('hidden');
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
}
};
document.onreadystatechange = () => {
if (document.readyState === 'interactive') {
if (location.hash !== '') {
scrollToElement(location.hash);
}
}
};
.hidden {
display: none;
}
<div style="height: 2000px"></div>
<div id="anchor" class="hidden">anchor</div>
This involves a bit of JavaScript. On load you can look for the Location: hash (that you already have in your URL). Do stuff to the page. In my example I create the element that gets the hash and then use Element.scrollIntoView() to navigate to that element.
window.location.hash = 'test'; // For testing. This has already been set in the URL.
document.addEventListener('DOMContentLoaded', e => {
// find the hash
let hash = window.location.hash.slice(1); // slice: remove the '#'
// add a new element (or make is visible etc.)
document.querySelector('main').innerHTML = `<h2 id="${hash}">${hash}</h2>`;
// scroll to the anchor
document.querySelector(`#${hash}`).scrollIntoView();
});
main {
height: 2000px;
position: relative;
}
h2#test {
position: absolute;
top: 1000px;
}
<main><main>
I've been thinking about it and trying stuff out. I tried out solutions above answered by #ciekals11 and #chrwahl but couldn't get these working. Probably because I am too amateur with js/Jquery.
Anyways my solution looks like this.
$(document).ready(function() {
if (
window.location.href == "http://localhost/mypage/secondpage#extrainformation"
) {
$(".tabs h4").removeClass("tab-current");
$(".tabs ul li:nth-child(4) h4").addClass("tab-current");
$("#section1").fadeOut();
$("#section4").fadeIn();
$([document.documentElement, document.body]).animate({
scrollTop: $("#extrainformation").offset().top
}, 1000);
return false;
}
});
This probably isn't the best answer but it works. Any other recommendations and solutions are welcome.
Following is my code which I am using to load contents dynamically. The issues which I am facing are the following:
Following code has now disabled CTRL+CLICK shortcode to open a url in a new tab. The new CSS and JS are not applying if they are not already exist in the previous page. Kindly let me know how can I resolve above mentioned issues?
$(document.body).on("click", "nav a", function () {
topen = $(this).attr("href");
window.location.hash = $(this).attr("href");
$("#main_wrapper").load( topen +" #main_wrapper > *");
return false;
});
What you want to do is modify the handler to use prevent default instead of returning false. Then you can check how the user activated the button and can act accordingly.
$(document).ready(function() {
$('a').on('click', function(e) {
if(e.ctrlKey || e.button === 1) {
return;
}
e.preventDefault();
// Do the stuff when the anchor is just clicked.
});
});
You can examine the Fiddle
In terms of the JS and CSS not applying we would need a working example of this to be of more assistance.
So I am developing this site from scratch (first time ever) and I've made the general layout from the psd I made and everything is great, so I am now at the point where I want to refine the site a bit with some javascript effects-functions.
When I am at the index page, you have a banner, sidebar and content (articles). When I press the articles it goes to the article (obviously) but I want to make a custom loading page like this at 0:22:
https://www.youtube.com/watch?v=k1q6Y_snURw#t=20
I've got to make or find a gif but say I've done that, how would I add this to the site?
The articles are all in a class by themselves although I guess I would have to use the ID for each specific article to get it to go to the respective article.
EDIT: Pop this in a file and add a reference to it in every page that has a link:
function loadXMLDoc(name) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.addEventListener("load", transferComplete, false);
xmlhttp.open("GET", name, true);
document.getElementById("Loading").style.display = "block";
xmlhttp.send();
function transferComplete() {
document.write(xmlhttp.responseText);
history.replaceState(null, null, name);
}
}
function AJAXcallback(e) {
var e = window.e || e;
var href = e.target.getAttribute("href");
if (e.target.tagName !== 'A' || href[0] == "#" || href.substring(0, 11).toUpperCase() == "JAVASCRIPT:" || e.target.class == "noloadpage")
return;
e.preventDefault();
loadXMLDoc(href);
}
if (document.addEventListener)
document.addEventListener('click', AJAXcallback, false);
else
document.attachEvent('onclick', AJAXcallback);
And something to show when the next page is loading
(be sure to add the id "Loading") like this:
<div id="Loading" style="display:none">Loading</div>
This makes every link that isn't an anchor(#id) or function(javascript:whatever) and doesn't have the "noloadpage" class load with AJAX and show the Loading div while loading.
If i understand properly you want a smooth scrolling to the article. You can achieve this with using animate and scrollTop.
Is it possible to animate scrollTop with jQuery?
Now you need to select your article with a selector.
http://api.jquery.com/category/selectors/
Your saying that your article has is proper class. So the code will look like this :
$("sidebar").click(function () {
// "." is the selector for class and i assume the value of the sidebar match the class of article
$("html, body").animate({ scrollTop: $("." + $(this).val()).position().top });
});
Hope this help.
I'm using this fade in and out JQuery/Javascript effect on my site to have each page fade in and out when a link is clicked. It's working great when the link that is clicked leads to a different page, but it is causing problems when the link leads to a different part of the page (such as my back to top link), when a mailto link is clicked, and when a link that is suppose to open up in a new page or tab is clicked. When these type of links are clicked they just lead to a blank white page because they don't lead to a new page. Here is the script:
$(document).ready(function() {
//Fades body
$("body").fadeIn(1500);
//Applies to every link
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
//Redirects page
function redirectPage() {
window.location = linkLocation;
}
});
Because of this I'm trying to figure out if there is a way where I can exclude this fade in/out function from certain links (such as the back to top link), but I don't know how to do it. I know that rather than set all the links to fade in/out I can set the fade in/out effect to a specific class that way it doesn't effect every link. However because the site is rather large, it would be extremely tedious and difficult to add that class to every link. So rather than do that I'm wondering if theres a way to define a no-fade class that would exclude this fade in/out function? That way I could apply that class to these few links that are having problems and make those links behave normally.
It seems like a simple thing to do, but because I'm still not very fluent in javascript/jquery I don't know how to do it. Any help would be much appreciated!
*EDIT: Here is the solution incase anybody else has a similar issue. Thanks to David for the missing piece!
$(document).ready(function() {
//Fades body
$("body").fadeIn(1500);
//Applies to every link EXCEPT .no-fade class
$("a").not(".no-fade").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
//Redirects page
function redirectPage() {
window.location = linkLocation;
}
});
Yup, you could indeed define a class that when applied to an anchor would exclude it from performaing your fade out and redirect.
So if you had an anchor you wanted your default fade-out behaviour to apply to then simply leave it as is.If you didn't want this behaviour then you could apply a class (we'll call it *no-fade") to the anchor.
HTML
Another page
Back to top
jQuery
<script type="text/javascript>
$(document).ready(function() {
$("body").fadeIn(1500);
$("a").not(".no-fade").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
// Redirects page
function redirectPage() {
window.location = linkLocation;
}
});
</script>
The only thing I've edited from your code is the selection of the anchors which I changed from:
$("a")
to
$("a").not(".no-fade")
The unobtrusive way would be to look for the hash symbol (#) or mailto:, etc. to prevent those types of links from fading out:
working fiddle
$("a").click(function (event) {
event.preventDefault();
linkLocation = $(this).attr('href');
if(linkLocation.indexOf('#') != -1 || linkLocation.indexOf('mailto:') != -1)
{redirectPage();}
else if($(this).attr('target') && $(this).attr('target').indexOf('_') != -1) window.open(linkLocation);
else $("body").fadeOut(1000, redirectPage);
});
Also, linkLocation = this.href should be linkLocation = $(this).attr('href')
how can I disable or hide address bar and back and forward buttons in ie and firefox
i tried lots of links and solutions but non of them worked
for example for disabling back button:
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
but it seems that it goes to previous page then it returns
and i trid :
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
}
for disabling menu bar but it didnt work
what can i do
Instead of disabling the back button, try to make your page that supports users to going back. It will increase the usability of your application.
Even you can impliment it for the ajax activities also.
Don't think you can disable buttons on browser. I mean, otherwise, we'd seen it on spyware infected sites...
In terms of hiding them, I've seen banks use a full screen popup without those buttons (but hardware button on mouse or hitting backspace still works).
Not tested but you can bind to the window's hashchange event.
For example, in jQuery it very easy to do:
$(window).bind('hashchange', function(e)
{
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false; // stop event
});
The result is that the back button not changes the page when an anchor is in the url. But i agree with the first answer also (it is not a real answer i think, it is an advice).
You can also override the last entry in window.history, so user can't go back.