Afz Afz - 1 year ago 191
jQuery Question

How to use a dynamically generated id in window.location.href?

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download