Reputation:
I have 5-10 links all with the same class/
<a class="content-link" href="/profile/about-me/<? echo $row['username'];?>/">
What I'm trying to achieve is when the user clicks on this link that then the user is then navigated to the #profile-body
div using javascript.
Very similar to this post however the only difference is that instead of having the div which i want the user to be navigated to in the a href like so <a href="#profile-body">
I need it to be done via javascript so that the link I have in the href actually loads.
Thankyou in advance for any help you can provide.
Upvotes: 0
Views: 22777
Reputation:
This can also be done with pure CSS
.
body {
background: #999
}
.mylinks a {
text-decoration: none;
color: black;
display: inline-block;
padding: 2%;
background: #444;
color: #999;
}
.mycooldiv {
background: red;
width: 100%;
height: 400px;
margin-bottom: 30%;
box-shadow: inset 0 0 10px 200px rgba(0, 0, 0, 0.55);
}
#profile-section1 {
background: red;
bottom: 100%
}
#profile-section2 {
background: blue;
bottom: 200%
}
#profile-section3 {
background: green;
bottom: 300%
}
#profile-section4 {
background: yellow;
bottom: 400%
}
<body>
<div class="mylinks">
<a class="content-link" href="#profile-section1">section 1 </a>
<a class="content-link" href="#profile-section2">section 2 </a>
<a class="content-link" href="#profile-section3">section 3 </a>
<a class="content-link" href="#profile-section4">section 4 </a>
</div>
<div class="mycooldiv" id="profile-section1"></div>
<div class="mycooldiv" id="profile-section2"></div>
<div class="mycooldiv" id="profile-section3"></div>
<div class="mycooldiv" id="profile-section4"></div>
</body>
Upvotes: 3
Reputation: 8210
There's no reason to use jQuery though (unless you're using it already), this is a full vanilla approach. Setting the hash is optional.
Basically, this script is included on the new page, you set the hash manually and then just switch the offsetTop.
(function() {
window.location.hash = "three";
document.getElementById('three').offsetTop + "px";
})();
div {
height: 250px;
margin-bottom: 10px;
background-color: #F00;
}
<div id='one'>one</div>
<div id='two'>two</div>
<div id='three'>three</div>
Upvotes: 1
Reputation: 2251
The easy way of doing so is via JQuery:
$(".content-link").click(function () {
$('html,body').animate({ scrollTop: $(this.hash).offset().top }, 400);
});
With this, you have ALL your .content.link href controlled.
Anyway, it's worth to take a look at flesler/jquery.scrollTo
Upvotes: 0
Reputation: 6050
I'm aware you're looking for a Javascript solution but just in case you're willing to use Jquery here's a good one.
$(document).ready(function() {
$('.content-link').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('#profile-body').offset().top
}, 500);
});
});
Upvotes: 5