Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks

XHTML:

<div id="wrap">
      <h1>Show/Hide Content</h1>
      <p>
          This code snippet demonstrates how to create a show/hide container with links, div element, CSS styles, and JavaScript functions. Click on the "see more" link below to see it in action.
          <a href="#" id="example-show" class="showLink"
              onclick="showHide('example');return false;">
              See more.
          </a>
      </p>
      <div id="example" class="more">
         <p>
             Congratulations! You've discovered the secret hidden text! Click the link below to hide this content again.
         </p>
         <p>
             <a href="#" id="example-hide" class="hideLink"
                 onclick="showHide('example');return false;">
                 Hide this content.
             </a>
         </p>
      </div>
   </div>​

JavaScript:

function showHide(shID) {
   if (document.getElementById(shID)) {
      if (document.getElementById(shID).style.display != 'none') {
         document.getElementById(shID).style.display = 'none';
      }
      else {
         document.getElementById(shID).style.display = 'block';
      }
   }
}

CSS:

body {
    font-size: 62.5%;
    background-color: #777; 
}
#wrap {
    font: 1.3em/1.3 Arial, Helvetica, sans-serif;
    width: 30em;
    margin: 0 auto;
    padding: 1em;
    background-color: #fff; 
}
h1 {
    font-size: 200%; 
}
/* Custom CSS for Show/Hide functionality */
.more {
    display: none;
    border-top: 1px solid #666;
    border-bottom: 1px solid #666; 
}
a.showLink, a.hideLink {
    text-decoration: none;
    color: #36f;
    padding-left: 8px;
    background: transparent url(down.gif) no-repeat left; 
}
a.hideLink {
    background: transparent url(up.gif) no-repeat left; 
}
a.showLink:hover, a.hideLink:hover {
    border-bottom: 1px dotted #36f; 
}​

Live DEMO

Answer №1

When calling the showHide function from the HTML window, ensure that it has been defined beforehand. Simply include the showHide function within a <script> block in the HTML window to resolve this issue. For reference, you can view my jsfiddle example here: http://jsfiddle.net/HGbSX/1/

If you are experiencing the problem of having to click twice to show additional content, it may be due to incorrect logic implementation. Check if the display property of the element is not set to none, but actually an empty string initially, causing it to re-hide. To fix this, consider reversing your logic to check for display='block' instead. Another demonstration is available on my jsfiddle at: http://jsfiddle.net/HGbSX/2/

Answer №2

I managed to fix a minor bug where it required two clicks to start working properly. I simply switched out != 'none' with == 'block'. Additionally, in JSFiddle, the wrong setting was selected under the 'choose framework' section. It should have been set to 'head no wrap'.

http://jsfiddle.net/EMEL6/12/

Another simple way to achieve the same result:

function showHide() {
    $('#example').toggle();
}

Answer №3

Although the code is accurate, it may not be functioning correctly due to the configuration of your jsfiddle. By default, jQuery and onLoad are selected on the right side, resulting in the code being wrapped within a function as shown below:

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
function showHide(shID) {
   if (document.getElementById(shID)) {
      if (document.getElementById(shID).style.display != 'none') {
         document.getElementById(shID).style.display = 'none';
      }
      else {
         document.getElementById(shID).style.display = 'block';
      }
   }
}

});//]]> 

To remedy this issue, change the dropdown selection to 'no wrap (head)' to prevent interference with your JavaScript. This will allow onclick to properly access the defined function.

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

Modifying subtotal values using PHP and JavaScript

I've been working on this code snippet to calculate my subtotal and determine the total payment. Can someone provide some assistance? $viewx = mysql_query("select distinct toorderid from ordercontainer where toordercategory='$ordercategory' ...

When you use Greasemonkey to click a link embedded within the content

In need of assistance with clicking a dynamic link using Greasemonkey. The only static part of the code is the text 'Attack This Player'. The href attribute of the link changes depending on the page. Here is my current code: function click_elem ...

In the world of Express, the res.write function showcases the magic of HTML elements contained within

Currently diving into web app development, I have ventured into using express and implemented the following code snippet: app.post("/", function(req, res) { var crypto = req.body.crypto; var fiat = req.body.fiat; var amount = req.body.amount; va ...

Ways to detect events even after the object has been swapped out in JavaScript

I am currently developing a JavaScript-based Scrabble game and encountering a puzzling issue. The problem arises when tiles are generated within a tile rack div using a specific function, and an event listener is set up to respond to clicks on the tile div ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...

Unable to switch between navigation items and icons

Currently, I am in the process of learning vanilla JavaScript and I'm trying to incorporate a navigation feature similar to when the hamburger icon is clicked. However, I have encountered an issue where I cannot toggle the hamburger icon to change it ...

Having trouble getting Jquery autocomplete to function properly with a complicated array?

I started with the guidance provided in this post, which was successful. To investigate why it's not functioning, I made a JsFiddle but couldn't figure out the issue. Even when trying to search for results using the first letter of the last name ...

Creating a responsive button inside a table can be achieved effortlessly with Angular Material table components

Help needed to ensure button responsiveness within a table. Here's how it appears on desktop and mobile screens: Desktop View https://i.sstatic.net/GxHUe.png Mobile View https://i.sstatic.net/oOAgk.png The delete button is somewhat obscured in t ...

I'm looking to streamline my code by creating shared functionality across multiple reducers with the help of create

Previously, in the older way of using Redux, we could create a reducer like this - handling different action types but with the same action: export default function authReducer(state = initialState, action) { switch (action.type) { case AUTH_ERROR: ...

Incrementing counters within nested div elements

Looking to implement a counter-increment feature on ordered lists. The goal is for each ol to pick up where the previous count left off. The functionality is successful when there are no separate wrapping divs around the ols. However, the issue arises whe ...

What is the best way to retrieve the current quality label from JWPlayer using JavaScript?

My goal is to retrieve the Current Quality Label from JWPlayer 7 using JS, but instead of getting the defined labels like 360p, 480p, 720p, I'm only receiving numbers such as 1, 2, 3... This is what I've tried: playerInstance.getCurrentQuality( ...

What are the best practices for integrating RxJS into Angular 2 projects?

How can I write code like this in Angular 2? var closeButton1 = document.querySelector('.close1'); var close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click'); I have attempted various methods to incorporate this into an An ...

Deactivating the idle timer in React Native: A Step-by-Step Guide

Currently, I am working on an app that involves a timer using RN. However, I have noticed that after approximately 1 minute and 50 seconds, the device's screen starts to dim in preparation for sleep mode. ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

Looking to validate each input field individually using jQuery?

I am in need of validating all form inputs in the keyup function without having to write validation for each individual input. Is there a way to achieve this using methods like each();? Apologies for what may seem like a silly question. ' ...

What is the best way to prevent scrolling in one column while allowing another column to scroll normally?

On my website, I have two divs positioned side by side. I am looking to keep one div fixed without scrolling while allowing the second div to scroll normally. How can I achieve this? For a clearer visual, refer to this image: Sample Image ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map. let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...