I'm having trouble getting my JavaScript to function properly. It recognizes the ID, but for some reason, it is not implementing the display changes

I understand the importance of learning jQuery, but I prefer to delve into raw JavaScript first. Can someone assist me without the use of jQuery for better understanding? Thank you!

Hello, I'm fairly new to JavaScript and have recently started my learning journey. The navigation code that I've included below is functional, so I'll leave it untouched.

However, I'm facing an issue with the second block of code. I've been exploring event listeners and other concepts through online videos, and while everything seems to make sense to me, I'm still unable to achieve the desired outcome!

My goal is to display the div with the id "cs" when CSS is clicked, and similarly for HTML and JavaScript.

Unfortunately, I lack sufficient knowledge in JavaScript to troubleshoot this on my own. I'm completely stuck and unsure how to resolve the problem!

If anyone could provide assistance, I would greatly appreciate it. My frustration is mounting, and I can't seem to figure it out before bedtime!

Below is the code snippet, along with a link to the JS Fiddle: https://jsfiddle.net/pmj26o9p/2/

var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');

htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);

function contentShow() {
  var whichOne = this.attributes["data-id"].value;
  var switcheroo = document.getElementById(whichOne);

switcheroo.onclick = function() {

  if (switcheroo.style.display === "none") {
    switcheroo.style.display = "";
  } else {
    switcheroo.style.display = "none";
  }

}

EDIT: Upon reviewing the code again, I realize that even if it functions properly, it won't achieve what I intended. This will allow me to show/hide the clicked element, correct?

Instead, I aim to display the selected item while hiding/applying display:none to all others that remain unclicked.

Answer №1

Here is an example below that demonstrates how the selected block is shown while the others are hidden, in alignment with your EDIT comment.

var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');

function contentShow(el) {
  var whichOne = el.attributes["data-id"].value;
  var switcheroo = document.getElementById(whichOne);

  // display the selected block and hide the others
  switch (switcheroo) {
    case htm:
      htm.style.display = "block";
      css.style.display = "none";
      js.style.display = "none";
      break;
    case js:
      htm.style.display = "none";
      css.style.display = "none";
      js.style.display = "block";
      break;
    case css:
      htm.style.display = "none";
      css.style.display = "block";
      js.style.display = "none";
      break;
  }
}
<span data-id="htm" onClick="contentShow(this)" style="margin-right:10px;color:red; cursor:pointer">Click to show the HTML Block</span>
<span data-id="css" onClick="contentShow(this)" style="margin-right:10px;color:green; cursor:pointer">Click to show the CSS Block</span>
<span data-id="js" onClick="contentShow(this)" style="margin-right:10px;color:blue; cursor:pointer">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>

Answer №2

When you attach a second event handler to the switcheroo element and the click event is not triggered, nothing will happen.

To create a toggle function for the switcheroo variable, follow these steps instead:

function contentShow() {
  var whichOne = this.attributes["data-id"].value;
  var switcheroo = document.getElementById(whichOne);
  return toggleDisplay(switcheroo);
}

function toggleDisplay(elem) {
  if (elem.style.display === "none") {
    elem.style.display = "";
  } else {
    elem.style.display = "none";
  }
}

Answer №3

Disregarding your current inefficient practices, let's modify

var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');

htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);

function contentShow() {
  var whichOne = this.attributes["data-id"].value;
  var switcheroo = document.getElementById(whichOne);

switcheroo.onclick = function() {

  if (switcheroo.style.display === "none") {
    switcheroo.style.display = "";
  } else {
    switcheroo.style.display = "none";
  }

}

into something like:

var doc = document;
function E(id){
  return doc.getElementById(id); // you guessed it - same as document.getElementById, without typing it every time
}
var htm = E('htm'), css = E('css'), js = E('js');
contentShow = (function(){ // self-executing scopes off var showing - variable style assignment requires function definition before execution
  var showing = false;
  return function(){ // returns unexecuted function
    var ht = E('ht').style, cs = E('cs').style, jsc = E('jsc').style;
    if(showing){
      ht.display = cs.display = jsc.display = 'none'; showing = false;
    }
    else{
      ht.display = cs.display = jsc.display = 'block'; showing = true;
    }
  }
})();
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);

Check out the updated JSFiddle here.

If there are no other click Events on those Elements, you could even update

htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);

to

htm.onclick = css.onclick = js.onclick = contentShow;

Find the revised JSFiddle here

However, note that this method overrides previous Events of the same type.

Answer №4

Here is a modification of the solution provided by @K Scandrett that enhances scalability and flexibility:

var navItems = document.getElementsByClassName("nav");

//Add Event Listeners
for(var j = 0; j < navItems.length; j ++)
{
    navItems[j].addEventListener('click', showContent, false);    
}

function showContent(elem) {
  var selected = elem.target.attributes["data-id"].value;
  var targetElement = document.getElementById(selected);

  for(var k = 0; k < navItems.length; k ++)
  {
    var contentBlock = document.getElementById(navItems[k].attributes["data-id"].value)
    contentBlock.style.display = contentBlock === targetElement ? "block" : "none";      
  }
}
<span data-id="htm" style="margin-right:10px;color:red; cursor:pointer" class="nav">Click to display HTML Block</span>
<span data-id="css"  style="margin-right:10px;color:green; cursor:pointer" class="nav">Click to show CSS Block</span>
<span data-id="js"  style="margin-right:10px;color:blue; cursor:pointer" class="nav">Click to show JS Block</span>
<br/>
<br/>
<div id="htm">Some information about HTML here</div>
<div id="css" style="display:none">Information regarding CSS shown here</div>
<div id="js" style="display:none">Details about JavaScript content displayed here</div>

Answer №5

Are you searching for a JavaScript solution? It's great that you want to grasp JavaScript before delving into jQuery. However, here's an unconventional approach for you - solely using HTML and CSS.

.info {display:none;}
.info:target{display:block;}
<a href="#htm" style="margin-right:10px;color:red;">Click to show the HTML Block</a>
<a href="#css" style="margin-right:10px;color:green;">Click to show the CSS Block</a>
<a href="#js"  style="margin-right:10px;color:blue;">Click to show the JS Block</a>
<br/>
<br/>
<div id="htm" class="info">Some HTML info here</div>
<div id="css" class="info">Some CSS info here</div>
<div id="js"  class="info">Some JavaScript info here</div>

I've utilized internal page ID links and the :target selector. This method is more semantically sound and can be further enhanced through scripting without compromising semantics. Additionally, users have the advantage of bookmarking selections with this option.

CSS OPTION 2

This alternative accomplishes the initial display by employing absolute positioning, z-indexes, and background colors to conceal the original content.

.info {position:relative;}
.info > div {
  position:absolute;
  top:0;
  left:0;
  background-color:#FFF;
  z-index:10;
  display: none;
}

#htm
{
  display:block;
  z-index:1;
}

.info > div:target {
  display: block;
}
<a href="#htm" style="margin-right:10px;color:red;">Click to show the HTML Block</a>
<a href="#css" style="margin-right:10px;color:green;">Click to show the CSS Block</a>
<a href="#js" style="margin-right:10px;color:blue;">Click to show the JS Block</a>
<br/>
<br/>
<div class="info">
  <div id="htm">Some HTML info here</div>
  <div id="css">Some CSS info here</div>
  <div id="js">Some JavaScript info here</div>
</div>

Consider manipulating CSS classes with JavaScript for adding/removing them instead of directly changing the display property. This enables the use of CSS transitions, enhancing user experience.

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

Navigating through information using Axios in React JS

Issue Currently, I am facing a challenge while trying to iterate through the data retrieved from an API call using Axios in a React.js application. The response is successfully received, but I am encountering difficulties when trying to display the inform ...

The variable referenced is not defined, resulting in a TypeError

Having some trouble with my code.. function compare(string,pattern){ var patternUpper = pattern.toUpperCase(); // Convert pattern to uppercase var stringUpper = string.toUpperCase(); // Convert string to uppercase for(var i=0;i<stringUpper.length-1 ...

Error loading Google Maps in Bootstrap 3.0 modal due to incomplete loading

Embedding the jQuery location picker into the content box of a Bootstrap modal 3 can be done like this: HTML: <a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a> <div class="modal" id="myModal"> ...

The ng-model does not bind properly when the input value is set through JavaScript instead of directly from

I'm encountering an issue with a text box in my project. The data is being populated using JavaScript, which reads a QR code and sets the value accordingly. I am using ng-model to bind to a variable in my controller, and while it works perfectly when ...

Javascript problem: Trouble with event.clientX position

I found a great resource on learning javascript at this website, I'm having trouble understanding the code snippets in function XY(e, v), specifically these two lines: event.clientX + document.documentElement.scrollLeft and event.clientY + document ...

Oops! Issue detected: improperly configured csrf in Express JS 4

Seeking help to activate the csrf module within Express 4 for an existing project. This is the code I've implemented: var csrf = require('csurf') ... app.use(csrf()); Upon starting my application, I encounter this message: Error: miscon ...

Please indicate a width of 3 characters for the HTML input text

Is there a way to create an HTML text box that can only fit 3 characters exactly? I came across this code online: <input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/> This code creates a text box with a width of 10px ...

determining the 'top' and 'right' coordinates upon clicking

I encountered an issue with a table having a drop-down menu that was getting cut off when opened on the last line. After some experimentation, I came up with a solution to detach the drop-down menu from its parent element and then reposition it by setting ...

What are some strategies for receiving multiple responses with just one ajax request?

. I am having trouble grasping the concept of using ajax and how to get multiple responses while passing a single request. Can anyone provide me with a sample code to help me understand better? ...

Adjust the size of the input form

Trying to create this design: https://i.sstatic.net/rPSiN.png But currently stuck with this layout: https://i.sstatic.net/3k5bE.png I'm puzzled on how to resize the input field with an icon on the right while using col-md-12... Check out my code ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

storing data in a nested child object within an array

I am attempting to include variables into the existing JSON data that is received from an API whenever a user clicks on the add button. However, I encountered this error message: Cannot find a differ supporting object '[object Object]' of type & ...

React - What is the best approach to handling the state of numerous dynamically generated controlled inputs?

Currently, I am iterating through a returned user object and generating a form for each user. Each form is meant to capture 'Add Hours Worked' input data for the specific user. Here's a snippet of the returned user array: employees: [ ...

Opt for the Coldfusion page as the default option

Recently, I encountered an issue with two files in my project: index.cfm and index.html. My intention was for users to be directed to index.cfm as the default page. On rare occasions when the ColdFusion server is down (which unfortunately I cannot fix), o ...

jQuery Validation plugin designed for responding to changes in elements and sending asynchronous requests

I attempted to utilize the guidance provided in this particular query, but unfortunately, it did not yield any positive results. Below is a concise version of my HTML structure. In the scenario where a User initiates an Order for 6 routers, a situation may ...

Organize information received from a post request into a JSON template

I am attempting to automatically sort information from a post request. Each category is identified by a number (0 -> 1 -> ....) There is one title defined for each category with its respective number, for example: "0": "Are planes fly ...

I'm not quite sure how to properly load data from an external JSON file into Highcharts

I'm facing a challenge importing my JSON data into my JavaScript code. I am new to JS, so there might be a simple solution that I am missing. The complete code snippet I have is from an example: <!DOCTYPE HTML> <html> <head> < ...

What is the best way to format Json data from the Wikipedia API for a mobile application redesign?

I am interested in revamping sections of Wikipedia articles and integrating them into a mobile application. My attempt to use http://en.wikipedia.org/w/api.php?action=parse&format=json&page=New_York resulted in the JSON files containing Mediawik ...

Appears as though time is slipping away during date conversions

I seem to be experiencing a strange issue where I lose a day when transitioning between MySQL and my JavaScript code, and I can't seem to figure out why. When I insert a date into the database (for example, 10/14/12), it appears as 10/13/12 in the dat ...

What is the best way to implement a collapsible menu in a fixed sidebar for mobile devices using Bootstrap 4?

I have been searching extensively, but I have yet to come across the precise solution for what I am trying to achieve. Being new to coding, I believe that the answer is probably simpler than I realize. My goal is to develop a sidebar navigation that remai ...