When the hidden div becomes visible, automatically scroll to the content

Struggling a bit here and need some help. I have three buttons and three hidden divs. When a button is clicked, the hidden content appears. How can I automatically scroll down so that the revealed content starts at the top of the page?

<script type="text/javascript">
function showDiv(num) {
    document.getElementById('div1').style.visibility='hidden';
    document.getElementById('div1').style.height='0px';
    document.getElementById('div1').style.overflow='hidden';
    document.getElementById('div2').style.visibility='hidden';
    document.getElementById('div2').style.height='0px';
    document.getElementById('div2').style.overflow='hidden';
    document.getElementById('div3').style.visibility='hidden';
    document.getElementById('div3').style.height='0px';
    document.getElementById('div3').style.overflow='hidden';
    document.getElementById('div'+num).style.visibility='visible';
    document.getElementById('div'+num).style.height='10px';
    document.getElementById('div'+num).style.overflow='visible';    
}
</script>

My CSS:

#div1, #div2, #div3 {
    visibility: hidden;
    height:0px;
    overflow:hidden

}

.button {
    background-color: green;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 22px;
    cursor: pointer;
    font-family: Arial;
}

My buttons:

<input type="button" class="button" name="Showdiv1" value="Show Div 1" onclick="showDiv('1')" />
<input type="button" class="button" name="Showdiv2" value="Show Div 2" onclick="showDiv('2')" />
<input type="button" class="button" name="Showdiv3" value="Show Div 3" onclick="showDiv('3')" />
<div id="div1"> I'm div1 </div>
<div id="div2"> I'm div2 </div>
<div id="div3"> <form style="margin-top:1000px;height: 1000px;" id="form1">
        Form with huge data in it
        </form> </div>

A demonstration where div 3 contains a lengthy form that begins lower on the page: https://jsfiddle.net/cgrouge/Lx0pyg4L/

Answer №1

$(document).ready(function() {
 $('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});

Edit 1:

Click here for more information on smooth scrolling. You can implement this script to achieve smooth scrolling by ensuring your input tags are enclosed within an anchor tag.

Edit 2:

Check out this CodePen example for a demonstration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Unable to mutate a state variable in Vuex

I am working on updating my contact list whenever a different brand is selected. The goal is to clear the array of contacts associated with the current brand and then refill it with the new brand's contacts. However, I'm facing an issue in my Vu ...

What is the best way to implement lazy loading for a Vue Component?

I've been working on implementing lazy loading for a Login component by using <Suspense> and <template> with default and callback. Everything seems to be functioning properly, except that the Loading component does not disappear after the ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Invisible boundary line within the column

My task involves creating a table using div elements. The layout of the table includes two columns structured as follows: <div> <div class = "columnborder"><span>Some text for column 1</span></div> <div><span>Some ...

Is there a way to hide the thumbnail image when the title is hovered over without using CSS?

I'm currently using a simple jQuery script to switch between two thumbnails when hovering over a div. The code works perfectly for the .thumbs class, but I also want this functionality to work with the post titles. Unfortunately, adding the .headline ...

The React Redux Saga triggers multiple API calls in a loop

I'm encountering an issue while fetching records in redux saga. There seems to be a strange behavior where calling an action in useEffect from the class triggers multiple calls in a loop, leading to endless API requests. Could someone please point ou ...

What is the procedure for configuring custom request headers in Video.js?

Encountering this issue, I created a simple example using guidance from this documentation: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link href="https://vjs.zencdn.net/7.4.1/video-js.css" re ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

Problem with executing callback after saving Mongoose model

Currently, I am delving into Node.js by studying a book. Instead of simply copying and pasting the sample code provided in the book, I am taking the concept and incorporating it into my own code as a learning exercise. One specific example is a new user c ...

What is the best method for summing the numerical values of a JSON array?

I have a task to calculate the sum and average of integer values from an Array object. Here is the input array: Input: [ {"string": "John", "integer": 7}, {"string": "Margot", "integer& ...

Attempting to output properties from an Express/Mongo API by utilizing a React.js frontend

I am currently in the process of developing a simplistic fictional sneaker application with the MERN stack. While I wouldn't classify myself as a beginner, I'm also not an expert. I successfully created the backend and generated a json rest-api. ...

Navigate the div with arrow keys

Looking for an answer similar to this SO post on moving a div with arrow keys, could a simple and clear 'no' be sufficient: Is it possible to turn an overflowing div into a "default scroll target" that responds to arrow-up/down/page-down/space k ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file name ...

What is the method for displaying html files in a POST request?

This is the code snippet I am working with: app.post('/convert', function(req,res){ var auxiliar = "somo Ubuntu command line(this works)"; exec(auxiliar, function(err, stdout, stderr){ if(err){ console.log ...

My goal is to develop a .NET Web API without utilizing MVC in order to efficiently save and retrieve data from a SQL database

My goal is to develop a Web API in .NET without using MVC that can store and retrieve data from an SQL database. The aim is to then utilize this API in another web application by leveraging JavaScript. The data to be stored will include fields for Id, comm ...

Changing the display property causes ordered lists to shift towards the left

// Ensure the list is displayed when checked and hidden when unchecked. function toggleList(event) { let ol = document.getElementById('list'); if (event.currentTarget.checked) { ol.style.display = 'initial'; } else { ol.s ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

A comprehensive guide on transferring user input onto a php text file

I am trying to implement a feature in my PHP code where the contents entered in a text box are uploaded to a text file. However, I only want them to be written if the string contains a specific pattern. Here is the modified PHP code: <?php $data = $_ ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...