Afz
Afz

Reputation: 77

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.

Upvotes: 1

Views: 9517

Answers (6)

Jitendra Tiwari
Jitendra Tiwari

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

vijayP
vijayP

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

Atif Hussain
Atif Hussain

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

Prasad Raja
Prasad Raja

Reputation: 703

Try this With the animation

   function openDiv() {
           var myDivID = "#" + divID + "_myDiv";
            $('html, body').animate({ scrollTop: $(myDivID).position().top}, 1000);
        });

Upvotes: 1

Alper Şaldırak
Alper Şaldırak

Reputation: 1054

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

Upvotes: 0

koninos
koninos

Reputation: 5327

If you just need to scroll to the top of your window window.location.href = "#" will do just fine.

Upvotes: 0

Related Questions