This seems like a trivial question but for some reason, I can't get an internal link to work properly.
I have 2 internal links (shown in the screenshots) on this page - https://www.top10metalbazookas.gq/products/elevar-arc-racer-us
When I click on this link it scrolls down to the correct section on the page
However, when I click on this link, nothing happens
For reference, the href attributes for both a tags have this as the ID.
#shopify-section-es-us-product-template-reviews
Is this some event propagation issue or some other kind of CSS bug or am I doing something silly here?
I've resolved this through jQuery for now. Since it's urgent. But I don't think it's the best option. If anyone has a hunch as to why the simple internal scrolling didn't work, please let me know.
This is how I did it:
function(t) {
t.preventDefault();
var e = $(this).attr('href');
$(e).trigger('click'), setTimeout(function() {
$('html,body').animate({
scrollTop: $(e).offset().top - 100
},
800,
'swing'
);
}, 300);
}
Related
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)
You know those webcams you can control over the internet? When you push the button to go left, it moves to the left.. but nothing else happens on the page.. Thats what I need to create.
I have a page that allows me to control lights in my house. When I click the button, I now have it load the php script (that controls the light) in a separate frame.. but I want to get rid of this. So basically I want to create a link that will call the php in the background, but that link won't do anything to the page its on.
Any ideas?
Use a return false; in the click event:
Not Follow the Link
Explanation
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.
You will need to use ajax to achieve such a behavior.
Links that don't do anything are basically HTML links where you bind the onclick event to a JavaScript function which returns false. This makes the links "do nothing" but still executes the JavaScript which tells the camera to go left/right.
HTML 5 let's you officially use anchor elements without a href attribute. But I would just bind a Javascript event listener to whatever element your already have. I'd even add these kind of interactive elements themselves to the DOM with Javascript, since they don't serve any purpose if a user has JS disabled.
...
will give you text that looks like a link.
If it's not really a link you may wish to consider a different kind of styling to emphasize the point and so that other underlined links show as links and this shows as something else. All depends on your needs and the situation.
I like jquery...
You will notice that the onclick function returns false. This is to stop the link from working...
<a onclick="do_it(this)" ...
then in your js
function do_it(anchor)
{
jQuery.ajax(
{
url : anchor.get_attribute('href'),
data : {whatever},
type : 'POST',
success : function(data)
{
alert('woo');
}
}
)
return false;
}
Pretty much what I'm doing here is:
So when the anchor is clicked jquery POSTs to the anchor's url. You can include data if you need to. This happens asynchronously so nothing happens on your page until jQuery gets response html(or whatever). If you want to do anything with the response you can get hold of it in the success function.
When the function returns it returns false, thus preventing the anchor from doing it's usual thing.
you talking about the javascript, create a onlick event / function and implement AJAX in specific DIV area
please check this out:
http://www.w3schools.com/ajax/ajax_examples.asp
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
//You need `ajax_info.txt` file with some content
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You can use the following jquery solution:
HTML:
Move lights to left
JQUERY:
<script type="text/javascript">
$(document).ready(function() {
$('#link1').click(function(e) {
e.preventDefault();
$.ajax( $(this).attr('href') );
});
});
</script>
Can't believe no one has posted this yet. just use javascript void:
some click function
Its one of the oldest tricks in the book!
You need Ajax to retrieve datas from PHP without loading another page.
To "disable" the link:
Link
Or:
Link
Or just write a normal link and use jQuery (or another library) to add the event:
$('a').click(function(event) {
// the code with ajax
event.preventDefault();
});
I have just solved an issue I had which couldn't be solved (to my limited knowledge) with an ActionLink so I used a regular hyperlink.
When these two links are rendered on the page, they are styled very similar to each other as they pass the same css conditions, however they aren't exactly the same in two ways that I have noticed:
The text is selectable on the hyperlink where is isn't on the ActionLink
When hovering over the ActionLink, the cursor changes to a hand rather than a pointer, the hyperlink stays with the pointer.
I was under the impression that an ActionLink renders a hyperlink which would explain why they are both styled by the css, but there are obviously some differences.
Does anyone know how to fix this, or suggest another solution to replacing an ActionLink with a hyperlink to call an AJAX function (which returns a PartialView)?
UPDATE
This is the rendered HTML. The first is the hyperlink, then second is the ActionLink.
<li><a id="load-partial">Test</a></li>
<li>Contact</li>
The reason I have an id in the hyperlink is so that it will run the following script to create the view in a specific div. I can't seem to replicate this using an ActionLink as it just return the view on it's own without the Layout views and completely unformatted.
<script>
$(document).ready(function () {
$('#load-partial').click(function () {
$.ajax({
url: '/Contact/List/',
datatype: 'html',
success: function (data) {
$('#adminmain').empty().html(data);
}
});
});
});
</script>
Thanks very much.
An ActionLink is nothing more than a server-side helper method that emits an HTML A tag. There is nothing else special about it.
If you are seeing differences in behavior / rendering, view the HTML source that is rendered and look for differences there.
There are very few things you cannot accomplish with an ActionLink that would require you to hand-code the A tag. Did you post a separate question about the problem you could not solve using it?
UPDATE (based on your posted HTML)
The hyperlink is missing a href so it will not do anything when clicked.
If you need to add an ID to your ActionLink, you can do something like:
#Html.ActionLink("Contact (this is the text)", "List", "Contact",
new { someQueryStringParameter = 42 },
new { id="load-partial" })
That example shows how to generate
<a id="load-partial" href="/Contact/List?someQueryStringParameter=42">Contact (this is the text)</a>
Keep in mind the ID should be unique on a given HTML page.
I have been playing around for ages with this and it does not seem to work.
I am looking to add a hidden voucher code function to my site and have it so that the code is actually hidden until the "click to reveal" button is clicked and user's browser opens a new window.
I have a test page with exactly what i'm talking about.
my trouble is, everything works but the actual voucher reveal bit.
Any ideas, or any link on how to do this?
Your page looks like you're trying to use jQuery code, but you have not added jQuery to your document, and thus are receiving errors like Uncaught ReferenceError: $ is not defined.
See jQuery: The Basics on how you can set up your page to point to jQuery properly.
As Jonathan Newmuis pointed out, your missing the jQuery lib from your code. Which that is issue one, issue two is I don't see the fancybox plugin being called in either.
so where you have this bit
<script type="text/javascript">
$(document).ready(function () {
$(".popUpCode75554").fancybox({
'overlayOpacity': 0.7,
'enableEscapeButton': false,
'hideOnOverlayClick': false,
'hideOnContentClick': false,
'showCloseButton': true,
'frameWidth': 520,
'frameHeight': 400,
'overlayColor': '#000000',
'callbackOnClose': function () {
$('.voucher-code-revealed-75554').show();
$('.voucher-buttons-75554').hide();
}
});
$(".cashbackWarning").fancybox({
'overlayOpacity': 0.7,
'enableEscapeButton': false,
'hideOnOverlayClick': true,
'hideOnContentClick': false,
'showCloseButton': true,
'frameWidth': 500,
'frameHeight': 250,
'overlayColor': '#000000'
});
});
try {
var pageTracker = _gat._getTracker("UA-11279427-1");
pageTracker._setDomainName("none");
pageTracker._setAllowLinker(true);
pageTracker._trackPageview();
} catch(err) {}
</script>
add the following above it.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="http://yandex.st/jquery/fancybox/1.3.4/jquery.fancybox.min.js"></script>
not sure how old/new that particular fancy box version is compared to the one you are attempting to use but I think it may be the newer of them. Anyway. adding those 2 lines may solve your problems unless the code you have otherwise currently is flawed somehow which doesn't appear to be the case at the moment.
On another note, if you use firefox might I suggest getting yourself an addon called firebug, it will aid you in debugging javascript based errors as well as other things.
Using mootools.js 1.3.2 and mootools-more.js
As far as I can tell this is supposed to reveal the div and also hide the content and linkTab divs at the same time.
$('blogLink').addEvent('click', function(){
$('homeLink').removeClass('active');
$('linkTab').removeClass('active');
$('blogLink').addClass('active');
content.slideOut();
linkTab.slideOut();
blogLink.slideIn();
});
This is the HTML
Blog
<div id="blogContent">
content here
</div>
It all works properly and that's OK but in addition to this, I also want to be able to give people a URL like http://mysite.com/#blogLink and have that blogContent div opened. When I do that now, it takes me to the top of the page and the blogContent div is hidden.
How do I do achieve that? I did try adding the mootools-smoothscroll.js and using the method outlined here http://davidwalsh.name/smooth-scroll-mootools but that just broke the entire page - would not load properly.
I have zero experience with mootools and weak on Javascript so please excuse me if I take a while to 'get' what you're trying to explain.
Many thanks.
First, are you particularly attached to MooTools? If you're a JavaScript newbie, jQuery is probably easier to use and definitely has a larger support community. But I'll post a solution that should work in MooTools for now:
If I understand you correctly, what you want to achieve is the following:
The anonymous function you posted will run when "Blog" is clicked
The function will also run if someone visits the page with #blogLink in the URL.
That's not too difficult to achieve:
// Once the DOM has loaded - so that our elements are definitely available
window.addEvent('domready', function() {
// Check for #blogLink hashtag, and reveal blog
if(window.location.hash == 'blogLink') { revealBlog(); }
// Make sure blog is revealed when link is clicked
$('blogLink').addEvent('click', revealBlog);
});
function revealBlog() {
$('homeLink').removeClass('active');
$('linkTab').removeClass('active');
$('blogLink').addClass('active');
content.slideOut();
linkTab.slideOut();
blogLink.slideIn();
}
You could also change your link mark-up to:
Blog
To make sure they're always on the correct link when the blog is revealed.