Reputation: 77
I have the following code in js and htm.
<div id="div1_myDiv">This is my div1</div>
<div id="div2_myDiv">This is my div2</div>
<div id="div3_myDiv">This is my div3</div>
<div id="button1" onclick="openDiv('div1')">Show div1</div>
<div id="button2" onclick="openDiv('div2')">Show div2</div>
<div id="button3" onclick="openDiv('div3')">Show div3</div>
Whenever a button(div) is clicked, the page should scroll to the top of the div.
function openDiv(divID) {
var myDivID = "#" + divID + "_myDiv";
window.location.href = myDivID;
}
This doesn't seem to work. Please advise a solution.
This question was marked as a duplicate of div scroll to in javascript but that didn't help.
Upvotes: 1
Views: 9517
Reputation: 1691
You need to concate
myDivID in existing URL
.
Try this solution
function openDiv(divID) {
//alert(divID);
var myDivID = "#" + divID + "_myDiv";
//window.location.hash = myDivID;
window.location.href=window.location.href.concat('#Id');
console.log(window.location.href);
}
<div id="div1_myDiv">This is my div1</div>
<div id="div2_myDiv">This is my div2</div>
<div id="div3_myDiv">This is my div3</div>
...
<div id="button1" onclick="openDiv('div1')">Show div1</div>
<div id="button2" onclick="openDiv('div2')">Show div2</div>
<div id="button3" onclick="openDiv('div3')">Show div3</div>
Upvotes: 0
Reputation: 11502
Could you please modify your function openDiv()
in following way:
function openDiv(divID) {
var myDivID = "#" + divID + "_myDiv";
window.location.hash = myDivID; //setting the location.hash
}
Upvotes: 3
Reputation: 898
"window.location.href" is use to change the current web page of the browser. for your task, you can use the anchor tag element to show the div section. just like below,
<div id="div1_myDiv">This is my div1</div>
<div id="div2_myDiv">This is my div2</div>
<div id="div3_myDiv">This is my div3</div>
...
<a id="button1" href="#div1_myDiv">Show div1</a>
<a id="button2" href="#div2_myDiv">Show div1</a>
<a id="button3" href="#div3_myDiv">Show div1</a>
Upvotes: 0
Reputation: 703
Try this With the animation
function openDiv() {
var myDivID = "#" + divID + "_myDiv";
$('html, body').animate({ scrollTop: $(myDivID).position().top}, 1000);
});
Upvotes: 1
Reputation: 1054
function popitup(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
Upvotes: 0
Reputation: 5327
If you just need to scroll to the top of your window window.location.href = "#"
will do just fine.
Upvotes: 0