JavaScript Expandable Divs: Create versatile and dynamic div elements

I have successfully implemented the expandable feature, but I am looking for a way to make the "read more..." link disappear once it is clicked. Despite browsing through StackOverflow for code and solutions, I cannot seem to find a solution that makes the link vanish.

Here is the code snippet:

<p style="text-align: center; font-size:18px; font face=nerislight; color:#009cdc">Test title test title test title</p>

<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
var i = document.getElementById(a + '_image');
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"} else {
e.style.display="none"}
return false;
}
</script>

Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy Test copy </p>

<p style="text-align: center; font-size:14px; font face=nerislight"><a style="cursor:pointer;" onclick="return toggleMe('landworks')">Read more...</a>

<div id="landworks" style="display:none;">Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion </p>

<strong>More Expansion</strong>Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion </p>

<p style="text-align: center;">Call to Action</p>

<div class="mk-button-align center"><a href="http://atestpage.com" id="123" class="mk-button dark button-190 light-color  mk-shortcode three-dimension small  ">Contact us today!</a></div>

<style type="text/css">
.button-190 {
            margin-bottom: 0px;
            margin-top: 0px;

    }

    .button-190 {
            background-color:#009cdc;

    }

     .button-190:hover {
            background-color:#0091cd;

    }
    .button-190.three-dimension  {
         box-shadow: 0px 3px 0px 0px #007db0;
    }
    .button-190.three-dimension:active  {
         box-shadow: 0px 1px 0px 0px #007db0;
    } 
</style>
</div>

Essentially, I want the "read more..." link to disappear once clicked so that it looks like regular text. Currently, the link remains visible on the page after clicking, causing an awkward break in the content. Can anyone provide assistance with this issue?

PS: I would love to showcase it on JSFiddle for better understanding, but I am new to JavaScript and uncertain how to do so.

Answer №1

To hide the paragraph labeled "read more," it is necessary to execute the toggleMe function beforehand.

Once you click this, the display will be hidden: onclick="this.style.display='none';return toggleMe('landworks')"

You can witness the functionality within your code by visiting this jsfiddle: http://jsfiddle.net/p8v9qpdL/

Answer №2

For those looking for a solution, this code snippet should do the trick: Click here to view the code

<p style="text-align: center; font-size:18px; font face=nerislight; color:#009cdc">Example Title Example Title Example Title</p>

<script type="text/javascript">
function showHideContent(a){
var element=document.getElementById(a);
var image = document.getElementById(a + '_image');
var readMore = document.getElementById('read-more');
readMore.style.display="none";
if(!element)return true;
if(element.style.display=="none"){
element.style.display="block"} else {
element.style.display="none"}
return false;
}
</script>

Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text Sample text </p>

<p style="text-align: center; font-size:14px; font face=nerislight"><a id="read-more" style="cursor:pointer;" onclick="return showHideContent('landworks')">Show more...</a>

<div id="landworks" style="display:none;">Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion </p>

<strong>Additional Details</strong>Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion Expansion </p>

<p style="text-align: center;">Take Action Now</p>

<div class="mk-button-align center"><a href="http://examplepage.com" id="123" class="mk-button dark button-190 light-color  mk-shortcode three-dimension small  ">Contact us today!</a></div>

<style type="text/css">
.button-190 {
            margin-bottom: 0px;
            margin-top: 0px;

    }

    .button-190 {
            background-color:#009cdc;

    }

     .button-190:hover {
            background-color:#0091cd;

    }
    .button-190.three-dimension  {
         box-shadow: 0px 3px 0px 0px #007db0;
    }
    .button-190.three-dimension:active  {
         box-shadow: 0px 1px 0px 0px #007db0;
    } 
</style>
</div>

Answer №3

I created a simplified version of this to make it easier to identify the issue.

Essentially, what happens is that it listens for a click, then adjusts the height of the article (which contains all the content) and hides the button.

The CSS styles used are overflow: hidden (to hide any overflowing content) and a fixed height.

read_more.addEventListener('click', function () {
    main.style.height = 'auto';
    read_more.style.display = 'none';
});

http://jsfiddle.net/snlacks/5f2qpx04/

Answer №4

Assign an identifier to the anchor element and corresponding identifiers to the content div using standardized suffixes for your ids. Include the prefix for these ids in your toggle_me function to simultaneously change the visibility of both the link and the content:

<a id='landmark-read-more' onclick='return toggle_me("landmark")'>Read more...</a>
<div id='landmark-content'>Content</div>
<script type="text/javascript">
function toggleMe(a){
  var contentDiv=document.getElementById(a+'-content');
  var toggleLink=document.getElementById(a+'-toggle');
  if(!contentDiv)return true;
  if(contentDiv.style.display=="none"){
    contentDiv.style.display="block";
    toggleLink.style.display="none";
  } else {
    contentDiv.style.display="none";
    toggleLink.style.display="block";
  }
  return false;
}

</script>

As a side note: Currently, there is no option for the user to collapse the expansion, so there is no immediate necessity for the toggle function to include setting the display to none.

Answer №5

For our website, I have implemented a div expansion that functions similarly to the one used on this live example. In my version, I didn't hide the clickable text in the live version, but by simply adding this line of code in my jQuery, it effectively hides the targeted class:

        $('.yourClassHere').toggle();

You can check out how this works in action in this fiddle, which also includes a simplified expanding area.

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

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

`Slide align center in the bxslider``

I am attempting to create a slider that is centered on the view. The slide in the center should be positioned at the center of the red line(div). This is my attempt: https://fiddle.jshell.net/4xgpgng1/1/ <style> div.bxslider { margin:0 50%; text-al ...

Error: JavaScript function call did not provide a return value

Currently, I am in the process of creating a straightforward angular2/expressJS application. Within my expressJS code, I have an HTTP GET router call that retrieves all users from MongoDB and successfully returns them: app.get('/getusers', funct ...

Could HTML code be inserted into the <Head> section of a NextJS page?

I need to add meta tags retrieved from the backend for a certain page to the Head section of my page component. In React, I know that I can incorporate HTML using <div dangerouslySetInnerHTML={{__html: response.someHtml}} />. Can this same method b ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

Poorly positioned text displayed inline in HTML

My attempt to place a title in a div toolbar next to some images has hit a snag. The text is not aligning correctly; it should be positioned at the top of the toolbar, but it stubbornly remains at the bottom without budging. I wish for it to be vertically ...

Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file: $('#form-name').submit(function(ev ...

Sending a value to a specialized component

Presently, I am using a custom component called Search. This component is responsible for rendering a dropdown menu with different options based on the data provided. It also includes a None option by default. const Search = (props) => { const { type: ...

Encountering a Blank Area at the Top of a Printed AngularJS Screen

Currently, I am tackling an issue in AngularJS while working on the Print Invoice Page. The problem I am encountering is a blank space at the top of the printed screen. Check out the image here Below is my code: HTML <div id="invoice" class="compact ...

Can we find a solution to optimize "Crystal Reports" for mobile browsers and make it responsive?

I'm in the process of making my entire Asp.net application responsive for mobile browsers by utilizing Bootstrap. However, I've encountered a challenge with making Crystal Report responsive for mobile browsers. If anyone has any advice on how to ...

Identifying the completion of scrolling within a container

I'm facing a challenge with my dynamic website that has numerous blog posts. My goal is to initially load only four posts and then add another four as the user scrolls to the end of the page. While I have figured out how to handle this on the backend, ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

decoding json field containing forward slashes using javascript

Seems easy enough, but I'm having trouble figuring it out. let data="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:&bs ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

JavaScript's getElementById function may return null in certain cases

I am studying JavaScript and I have a question about the following code snippet: document.getElementById('partofid'+variable+number). Why isn't this working? Check out these examples and JSfiddle link. I want the "next" button to remove th ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

Evaluate my API Manager

Hello, I am currently diving into the world of JavaScript backend development. My latest project involves building a RESTful API using node.js, express.js, sequelize.js with MySQL as my database. To test my skills, I have successfully created a basic Tasks ...

The content is not visible following the quotation mark

Once my script is executed, the input field ends up looking like this: <input type="text" value="How do you " /> Even if I try to escape the quotes or change them to &quot;, it still doesn't seem to work. Do you have any suggestions? $(& ...