Increase the size of <p> upon clicking on <h1> with the use of javascript, css, and html without relying on jquery

Upon loading the page, I want all my paragraph texts to be collapsed. Clicking on the heading should then expand the paragraph text accordingly. Each heading is followed by a single paragraph. As part of my current course, I am unable to utilize JQuery for this functionality. All blocks are enclosed within a div with the class "maincontent". Please refer to the following code snippet:

    <div class="maincontent">
        <h2>How HowziTO came to be? </h2>
            <p>
                This website was created by me, a South African who moved to Toronto in my mid 20's. Through the move, I felt unprepared, and at times, alone. Although there are many sites that offer advice to new immigrants,
                I thought it would be useful to create a site that is specific to South Africans, given our unique heritage. 
                So, if you feel like I felt, hopefull this website will help you settle in a little easier.
                If you have any suggestions for the site, please feel free to reach out to me using the <a href="About.html">the about page</a>.
            </p>
    </div>

Your assistance on this matter would be greatly appreciated. Thank you.

I have included a screenshot of my website below. The text under "How HowziTO Came to be?" should remain collapsed until the heading is clicked, expanding the text. The same behavior is desired for the other two headings as well.

Website

Answer №1

To implement this functionality in your code, simply assign an 'id' to your p tag and then pass that id as a parameter to the onclick function handler on the h2 tag as shown below -

<div class="maincontent">
   <h2 onclick="expand('p1')">How HowziTO came to be?</h2>
   <p id="p1">This website was created by me, a South African who moved to Toronto in my mid 20's. Through the move, I felt unprepared, and at times, alone. Although many sites offer advice to new immigrants,
   </p>
</div>

Don't forget to include display: none; for the p tag in your CSS.

Then, add JavaScript code like the one provided below -

expand = id => {
    let pTags = document.querySelectorAll('p');
    pTags.forEach(ptag => {
        ptag.style.display = 'none';
    });
    document.getElementById(id).style.display = 'block';
};

Whenever you add a new p tag, make sure to give it a unique id and pass that id to the expand function in the corresponding h2 tag. This function will automatically hide other tags and display the required one.

Answer №2

Thank you to everyone who offered their assistance. After carefully reviewing the provided options, I ultimately decided to implement an onClick function. Below is the JavaScript code I used:

function toggleParagraph(event) {
    var clickedHeading = event.target;
    var paragraph = clickedHeading.nextElementSibling;
    var table = paragraph.nextElementSibling;
    if (paragraph.classList.contains("displayme")) {
        if (paragraph.style.display === "none") {
            paragraph.style.display = "block";
            table.style.display = "block";
        } else {
            paragraph.style.display = "none";
            table.style.display = "none";
        }
    }
}

I needed to include the following in my HTML:

<h2 onclick="toggleParagraph(event)">

and

<p class="displayme">

Additionally, I added the following CSS properties:

.displayme {
    display: none;
}

and

table {
display: none;

With these changes, I was able to toggle the visibility of elements on and off as needed.

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

Determine the number of lines in a textarea, taking into account both manual

I have a textarea that I need to validate for input exceeding 6 rows. My JavaScript code works perfectly by checking for scrollbar presence, indicating more than 6 lines of input. However, how can I achieve the same validation using PHP in case JavaScript ...

Turn off cursor:pointer for disabled checkbox labels

Is there a way to apply the cursor:pointer style to checkboxes and their labels, but only for those that are not disabled? This is the code snippet I am currently using: <label> <input type="checkbox" ...more attributes... ...

Is the NodeJS rmdir function experiencing issues specific to LINUX?

Currently, I have a NodeJS script section that runs on my Windows 10 machine with the latest Node version and another version on my CentOS8 Linux webserver. The code executes as expected on Windows but throws an error when running on Linux at this specific ...

Are there any conventional methods for modifying a map within an Aerospike list?

Attempting to modify an object in a list using this approach failed const { bins: data } = await client.get(key); // { array: [{ variable: 1 }, { variable: 2 }] } const { array } = await client.operate(key, [Aerospike.maps.put('array', 3).withCon ...

Brainstorm: Creative ways to showcase excess content within a div

I'm struggling to find a suitable title for this issue. Essentially, I have a box-shaped div that expands into a rectangle and reveals content when clicked. The problem arises when I animate the div's width during expansion. Instead of positioni ...

Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount? In the image provided below, we have the Base Price. This base price may include multiple discounts. Each disc ...

Unique CSS animations that vary before and after

Looking to enhance a navbar with some interactive effects: Upon hovering over an item, I want it to disappear and be replaced by the same text in a different color. After the initial animation, I'm interested in adding another effect like a 360-degr ...

Whenever I navigate to localhost:3000 while using Next JS, it redirects me to 'http://localhost:3000/public/index' and displays a 404 error

In my pages folder, I don't have a public folder. Instead, I have the index.js file directly inside the pages folder. However, when I start the server at localhost:3000/, it automatically redirects to http://localhost:3000/public/index and displays a ...

The Redux store is duplicating the state across different reducers, causing it to appear twice

Having Trouble Viewing Different States for Two Reducers in Redux DevTools In my React project, I am attempting to incorporate a second reducer using Redux to gain a better understanding of the overall state. However, when I inspect the state in Redux Dev ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...

Stylish CSS typography options for both Mac and Windows users

When browsing various websites, I've noticed that many of them showcase beautiful fonts without using images. Examples include The Firebug site and Happy Cog. It seems like web designers use CSS tricks and JavaScript to achieve this effect. I'm ...

Multer is experiencing difficulties in uploading files, yet it is not displaying any error messages

When setting up an application to create courses with images, I encountered an issue while using multer for image uploading. Despite adding multer to my route with upload.single('images'), the uploaded images were not appearing in the designated ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

Error on Laravel 7: Unable to retrieve resource - the server returned a 400 (Bad Request) status code

Seeking assistance with a technical issue involving Razorpay. I'm encountering difficulty passing a value from the controller to JavaScript in the view. The data-order_id field is not populating, resulting in the error mentioned above, indicating a nu ...

Effortlessly adjusting the height of a hidden background image

At this website, I'm utilizing the CSS3 Cover property within the Background rule to extend an image behind the header. Presently, I've had to assign a min-height of 500px to the header element for it to display properly. However, this is not th ...

Aligning the block both vertically and horizontally

I've been trying to center a red block both horizontally and vertically like shown in the picture below, but it's not positioned correctly. I'm using Bootstrap 4. Can anyone point out what's wrong? https://i.sstatic.net/3ZGg6.png .p ...

What is the best way to obtain a virtual in mongoose when a property is excluded?

Imagine I have a post Model with fields like UserId, Title, Desc, and a likes array which references UserIds. When querying, I have a virtual property to calculate the number of likes a post has: schema.virtual("numLikes").get(function () { return this. ...

What is the best way to verify the relationship between parent and children nodes in a tree structure?

Check out my Plnkr with nested loops of checkboxes: here Below is the HTML code for the nested loops of checkboxes: <ul> <li ng-repeat="continent in destinations"> <input type="checkbox" ng-model="continent.selected"> {{contin ...

Executing asynchronous actions with useEffect

Within my useEffect hook, I am making several API requests: useEffect(() => { dispatch(action1()); dispatch(action2()); dispatch(action3()); }, []); I want to implement a 'loading' parameter using async/await functions in the hook ...

Slideshow plugin glitch on Safari and Opera caused by jQuery implementation

My current project involves utilizing a fantastic plugin called Sequence.js for creating animations and transitions with CSS3 based on jQuery. I have set up a simple responsive fadeIn-fadeOut slideshow using this plugin. While everything works smoothly an ...