简体   繁体   中英

HTML onClick go to another div

I have a button on my webpage which when onClick I want it to show another div. However when I click the button it will flash in the url that it went to the correct div but then it will immediately redirect back to the main div, #home.

Code for button:

<input type="button" class="flip" value="Redirect To Div" onClick="window.location='#targetDiv'" />

When I click the the button the url will flash:

www.XXXXX.com/#targetDiv

Then go immediately to www.XXXXX.com/#home

Any ideas why it won't display the div?

Thanks

looks like your form has

       action=""

or

       action="#home"

instead of onclick call a function

      onclick="mylinkfunction()"

...

     <script type-"text/javascript">

       function mylinkfunction(e) {

       window.location.href="#targetDiv";

       /* need to stop the form sending of the form

        UPDATE as comment: This may not be exactly correct syntax 
        for stopping a form , look up preventing form submission */

       e.preventDefault();
       e.stopPropagation(); 

       }

     </script>

or if your form is irrelevent set it's action and remove the javascript allogether

     <form action="#targetDiv" method="get">
     <input type="submit" value="go"/>
     </form>

but then all you would need is actually this ..

    <a href="#targetDiv">click me</a>

if by "go to another div" you mean jump and scroll the page to a new location it is actually an anchor you need to go to

        <a name="targetDiv"/>

Reusable function to go to a particular div or section with href:

const dynamicHrefSetter = (href: string) => {
  if (typeof window !== 'undefined') window.location.href = `#${href}`;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM