Looking to toggle text back and forth with a simple click? Here's how!

My goal is to toggle the text ____ (a gap) back and forth with Word by simply clicking it. I prefer not to use a button, as I want the user to only need to click on the actual gap itself.

I came across this page which outlines exactly what I am looking for, particularly the CSS-Only approach. However, when I attempted to implement it using the TryIt Editor, either that method or the jQuery alternative didn't function properly.

Below is the snippet showcasing the CSS method:

</style>
#example {
 position: relative; 
} 
#example-checkbox {
 display: none;
} 
#example-checkbox:checked + #example:after {
 content: "Hide";
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background: white;
 }
</style>

<input id="example-checkbox" type="checkbox">
<label for="example" id="example">Show</label>

Answer №1

Your requirements are met with this code snippet.

<!DOCTYPE html>
<html>

<body>
  This code contains a paragraph with clickable words. Click on the word -&gt; <span id="word" onclick="toggle()">____</span> &lt;- Have you clicked on previous word.

  <p id="demo"></p>

  <script>
    function toggle() {
      var word = document.getElementById("word").innerHTML;
      if (word.split('_').join('').trim().length === 0) {
        document.getElementById("word").innerHTML = "word";
      } else {
        document.getElementById("word").innerHTML = "_____";
      }
    }
  </script>
</body>

</html>


Implementing Multiple Hidden Words

The script in the <head> section of the code controls the hidden words interchange.

  <script>
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
  </script>

To add more words for toggling, simply include them in the 'words' array. The words will automatically switch between underscores and the actual word when clicked.

span {
  color: red
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
  </script>

</head>

<body>

  <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself.
  </p>

  <script>
    function toggle(element) {
      if (element.innerHTML.split('_').join('').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp(value, "g");
      $("p#demo:contains('" + value + "')").html(function(_, html) {
        return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)"> ' + value + ' </span>')
      });
    });
  </script>
</body>

</html>


Displaying Underscores On Page Load

Instead of manually clicking to reveal the words, modify:

return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)"> ' + value + ' </span>')

to:

return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">____________</span>')

After updating, the code will appear as follows:

span {
  color: red
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
  </script>

</head>

<body>

  <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself.
  </p>

  <script>
    function toggle(element) {
      if (element.innerHTML.split('_').join('').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp(value, "g");
      $("p#demo:contains('" + value + "')").html(function(_, html) {
        return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>')
      });
    });
  </script>
</body>

</html>


Handling Both Singular and Plural Forms

To account for plurals and singulars, adjust:

var replacestr = new RegExp(value, "g");

to:

var replacestr = new RegExp('\\b'+value+'\\b', "g");

The final code now supports both forms:

span {
  color: red
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    var words = [];

    words.push('vocabulary');
    words.push('lexicon');
    words.push('lexicons');
    
  </script>

</head>

<body>

  <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array.
  </p>

  <script>
    function toggle(element) {
      if (element.innerHTML.split('_').join('').trim().length === 0) {
        element.innerHTML = element.getAttribute("word");
      } else {
        element.innerHTML = "_______";
      }
    }

    $.each(words, function(index, value) {
      var replacestr = new RegExp('\\b'+value+'\\b', "g");
      $("p#demo:contains('" + value + "')").html(function(_, html) {
        return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>')
      });
    });
  </script>
</body>

</html>

Answer №2

Are you seeing the results you anticipated?

<input id="example-checkbox" type="checkbox">
<label for="example-checkbox" id="example">Display</label>

It's important to note the for attribute in the label- it should correspond to the id of the input checkbox.

#example {
  position: relative;
  cursor: pointer;
}
#example-checkbox {
  display: none;
}
#example-checkbox:checked + #example:after {
  content: "Hide";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}
<input id="example-checkbox" type="checkbox">
<label for="example-checkbox" id="example">Display</label>

Answer №3

The identification of the checkbox must be included in the Label's for attribute.

#example {
  position: relative;
}
#example-checkbox {
  display: none;
}
#example-checkbox:checked + #example:after {
  content: "Display";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}
<input id="example-checkbox" type="checkbox">
<label for="example-checkbox" id="example">Hide</label>

Answer №4

<label id="example-five" for="example-five-checkbox">_____</label>

Check out this link for a helpful example: https://jsfiddle.net/n1rb2y57/ Make sure to select a background color in your CSS that complements the overall look of your website perfectly.

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

The jQuery click event appears to be malfunctioning

Attempting to create a basic calculator using jQuery, the code seems straightforward but nothing is happening when executed. It's as if the JavaScript file isn't linked properly. Below is the jQuery code snippet: function addNumber(num){ ...

Is it possible to attach a Vue component to more than one div element simultaneously?

import Selector from '@components/contactSelector' let vueInstance = new Vue({ components: { Selector }, data () { return { url: url, isFilter: false, type: 'external', selectedList: [] } }, rende ...

Positioning a text field and a button adjacent to each other within the same row

My challenge is to consistently position a textfield and a button side by side. The requirement is for the button to always be on the right side of the screen, while the textfield should take up the remaining width on the left side. I initially tried setti ...

Uncertain entities in Typescript

I used to use Flow for typing. How can I type an imprecise object? Here's the array I'm working with: const arr = [ {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text'}, ...

Ways to display form choices that are influenced by other form selections

In my form, the user is supposed to choose a specific item at the end. As they fill in the initial options, the subsequent fields below change dynamically. Here is an example: Type: { t1:{ Number of X:{ 1:{...} 2:{...} ...

Implementing a Model-View-Controller architecture with AJAX functionality

Recently, I encountered an issue while trying to refresh a div containing a PartialView using Ajax.BeginForm. This process had worked smoothly for me numerous times in MVC4, but with the switch to MVC5, things took a turn. Let me walk you through the step ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

HTML code with embedded messages

I am interested in creating a straightforward message forum system. My goal is to organize messages in a nested structure (answering questions). For my website, I want it to be in Hebrew (dir="rtl"). I am considering generating <ol> elements dynam ...

The feature "scrollTo" in mcustomscrollbar is not functional in Chrome, however, it functions properly in FireFox

It seems that there is an issue with the mcustomscrollbar "scrollTo" function not working in Chrome, although it works fine in FireFox. No errors are showing up in the console, so it appears to be a browser-specific problem. I even tested the functionali ...

The total sum of various divs containing a mix of numbers and letters

I have a group of div elements with the same class, each containing a value in the format (X1), (X2),... I need to add up these numeric values only, like 1 + 2 + .... Since these divs are generated dynamically, I won't know how many there will be. How ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Retrieve a solitary row of information from a MySQL column

Here is an example of a MySQL database with the main table containing fields such as id, name, age, and photos: Table main: 3 John 22 photo1.jpg photo2.jpg photo3.jpg ph ...

Performing an AJAX call using jQuery within a PhoneGap application to communicate with a Node JS server

I've searched everywhere online for a practical demonstration of a jQuery AJAX call to a Node JS server, but to no avail. Typically, a jQuery AJAX request to a PHP server follows this format: $("button").click(function() { $.ajax({url: "http://w ...

Stop all child components in React from mounting when the page loads

I am currently working on a single-page React application where I need to mount specific components at different times. However, all the components are loading simultaneously instead of one at a time. In my research on StackOverflow, I came across solutio ...

The expected number of calls for the callback function was not met

Our employee webpage is designed to make Ajax calls to the node.js web server in a continuous loop. The problem arises when the callback UpdateTeamArr is expected to be triggered multiple times based on the loop max and the number of department options a ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...

The ability to use the backspace and Ctrl + c (Copy) functions is restricted in input fields on FireFox

I have a form with input fields designed using semantic UI. I need the input field to only accept numbers, remove spaces, and allow copying from it using ctrl +c. After some investigation, I found this jQuery code that seems to satisfy my requirements per ...

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

Challenge with correct application of Bootstrap-vue styles

I've been struggling to get bootstrap-vue up and running. Whenever I try to copy and paste the navbar component from boostrap-vue.js.org, parts of it are missing and I can't figure out why. While I manage to create router links with b-links that ...

Is the Vue "Unchecking" feature not properly deleting data from the array?

I need to update my function to handle the removal of a networkAudience when its corresponding checkbox is unchecked. Currently, the networkAudience is being added to the array when checked, but not removed when unchecked. What changes should I make to en ...