What is the process for showing and hiding text when a div is clicked?

Hey, I'm completely new to web development and decided to practice some of the concepts I've been learning about.

I created a simple program that toggles between day and night. Clicking on the sun reveals the moon, and clicking on the moon reveals the sun. You'll notice that by default, the text "Good Afternoon!" and "Good Night!" are displayed. I would like the text "Good Afternoon!" to only appear when the sun is visible, and "Good Night!" to only appear when the moon is visible. Any guidance on how to achieve this would be greatly appreciated.

You can find the code in this fiddle.

I attempted to write code that would replicate the behavior of the existing program, but I am aware that it is not correct:

/*toggle text*/
if ($('#daytext').hasClass('visible')) {
  $('#daytext').removeClass('visible');
} else {
  $('#daytext').removeClass('visible');
}

Answer №1

To achieve the desired effect, you can utilize CSS properties.

Consider using visibility : hidden; and display : none;.

According to a resource found here, "Another common display value is none. Some specialized elements such as script use this as their default. It is commonly used with JavaScript to hide and show elements without really deleting and recreating them.

It's important to note the distinction between display and visibility. Setting display to none will make the element appear as if it doesn't exist. On the other hand, visibility: hidden; will hide the element while still maintaining the space it occupies as if it were fully visible."

Answer №2

Check out the updated fiddle.

To hide the default Good Night! text and toggle its visibility with a click using jQuery's show() and hide() methods, you can use the following code:

if ($('#orb').hasClass('sun')) {
    $('#daytext').hide();
    $('#nighttext').show();
    $('#orb').removeClass('sun').addClass('moon');
} else {
    $('#daytext').show();
    $('#nighttext').hide();
    $('#orb').removeClass('moon').addClass('sun');
}

Hope this solution is useful!

$(document).ready(function() {
  $('#orb').click(function() {

    /*Day and night toggle*/
    if ($('#orb').hasClass('sun')) {
    $('#daytext').hide();
      $('#nighttext').show();
      $('#orb').removeClass('sun').addClass('moon');
    } else {
    $('#daytext').show();
      $('#nighttext').hide();
      $('#orb').removeClass('moon').addClass('sun');
    }

    if ($('#sky').hasClass('day')) {
      $('#sky').removeClass('day').addClass('night');
    } else {
      $('#sky').removeClass('night').addClass('day');
    }

    /*toggle visible moonspots*/
    if ($('#moonspot1').hasClass('visible')) {
      $('#moonspot1').removeClass('visible');
    } else {
      $('#moonspot1').addClass('visible');
    }
    if ($('#moonspot2').hasClass('visible')) {
      $('#moonspot2').removeClass('visible');
    } else {
      $('#moonspot2').addClass('visible');
    }
    if ($('#moonspot3').hasClass('visible')) {
      $('#moonspot3').removeClass('visible');
    } else {
      $('#moonspot3').addClass('visible');
    }
    /*toggle text*/
    if ($('#daytext').hasClass('visible')) {
      $('#daytext').removeClass('visible');
    } else {
      $('#daytext').removeClass('visible');
    }

  });

});
#orb {
  height: 300px;
  width: 300px;
  border-radius: 100%;
  padding: 20px;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  botton 0;
  right: 0;
}

#sky {
  height: 100%;
  width: 100%;
}

.sun {
  background-color: #ffdd00;
  border: 10px solid #f1c40f;
}

.sun:hover {
  border: 20px solid #f1c40f;
}

.moon {
  background-color: #bdc3c7;
  border: 10px solid #eaeff2;
}

.moon:hover {
  border: 20px solid #eaeff2;
}

.night {
  background-color: #2c3e50;
}

.day {
  background-color: #aaecf2;
}

#moonspot1 {
  height: 50px;
  width: 50px;
  border-radius: 100%;
  float: right;
  margin: 20px;
}

#moonspot2 {
  height: 80px;
  width: 80px;
  border-radius: 100%;
  float: right;
  margin: 20px;
}

#moonspot3 {
  height: 150px;
  width: 150px;
  border-radius: 100%;
  float: right;
  margin: 20px;
}

.visible {
  background-color: #eaeff2;
}

#daytext {
  font-size: 50px;
  font-family: Optima;
}

#nighttext {
  font-size: 50px;
  font-family: Optima;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body id="sky" class="day">
  <div id="orb" class="sun">
    <div id="moonspot1"></div>
    <div id="moonspot2"></div>
    <div id="moonspot3"></div>
  </div>
  <div id = "daytext">Good Afternoon!</div>
  <div id = "nighttext" style='display:none'>Good Night!</div>
</body>

Answer №3

In order to streamline your code, I have simplified the classes that need to be toggled. By toggling only between the .day and .night classes, you can achieve the same outcome. I have utilized display: none to hide elements that are not relevant based on the current state.

$(document).ready(function() {
  $('#orb').click(function() {

    /*Day and night toggle*/
    if ($('#sky').hasClass('day')) {
      $('#sky').removeClass('day').addClass('night');
    } else {
      $('#sky').removeClass('night').addClass('day');
    }

  });
});
#sky {
  height: 100%;
  width: 100%;
}
.night {
  background-color: #2c3e50;
}
.day {
  background-color: #aaecf2;
}

#orb {
  height: 300px;
  width: 300px;
  border-radius: 50%;
  padding: 20px;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  botton 0;
  right: 0;
}
.sun {
  background-color: #ffdd00;
  border: 10px solid #f1c40f;
}
.sun:hover {
  border: 20px solid #f1c40f;
}
/* styling the #sky.night .sun to be the moon */
.night .sun {
  background-color: #bdc3c7;
  border: 10px solid #eaeff2;
}
.night .sun:hover {
  border: 20px solid #eaeff2;
}

/* common styles for the 3 moonspots */
.moonspot {
  background-color: #eaeff2;
  border-radius: 50%;
  float: right;
  margin: 20px;
}
/* hide moonspots during day */
.day .moonspot {
  display: none;
}
#moonspot1 {
  height: 50px;
  width: 50px;
}
#moonspot2 {
  height: 80px;
  width: 80px;
}
#moonspot3 {
  height: 150px;
  width: 150px;
}

.text {
  font-size: 50px;
  font-family: Optima;
  /* position & z-index to put text above other elements */
  position: relative;
  z-index: 1;
}
/* hide the irrelevant text based on day/night */
.day #nighttext {
  display: none;
}
.night #daytext {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body id="sky" class="day">
  <div id="orb" class="sun">
    <div class="moonspot" id="moonspot1"></div>
    <div class="moonspot" id="moonspot2"></div>
    <div class="moonspot" id="moonspot3"></div>
  </div>
  <div class="text" id="daytext">Good Afternoon!</div>
  <div class="text" id="nighttext">Good Night!</div>
</body>

Answer №4

If you're utilizing jQuery, there are various ways to achieve this. One solution is outlined below.

Within the $(document).ready() function, you can include the following code snippet.

$('#nighttext').toggle();

Subsequently, within your click function, the following actions can be taken:

$('#daytext').toggle();
$('#nighttext').toggle();  

An alternative approach would be to have a single div element for the text content and modify both the text and its class upon each click event.

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

Allow for separation amongst my cellular components

I have a table with multiple cells and I would like to add some spacing between each <td> element. You can find an example of my code on JSFIDDLE. .line { border-bottom:1px solid black; } .textRotation { -webkit-transform: rotate(-90deg); ...

How do I navigate to a different page in a Flask app after an ajax post depending on a condition detected in the view?

Within my flask application, I have a sales page where users can input information that is then saved to the database using an ajax post request. The twist is that there are only a limited number of consoles available for users to record their sales. If on ...

Display the primary element at the beginning with jCarouselLite

I am working on a carousel feature that utilizes the jCarouselLite script to function as a sub menu within a webpage. After selecting an item from the carousel, the corresponding li element receives a class of active, with only 4 elements visible at a tim ...

The presence of CSS rollovers on a scrollable div is causing overflow problems

Currently, I am developing an interface that involves a list of items inside a scrollable div. Some of these items have rollover menus that extend beyond the boundaries of the div when hovered over. It is crucial for the website to be compatible with disab ...

HTML/CSS border tiling (left, bottom, right)

Is there a way to implement borders using images in CSS/HTML that does not involve CSS3? I am working with three border tiles: left, right, and bottom. I want them to repeat-x/y to the left, right, and bottom of my content container. I attempted to use d ...

Delete a specific character sequence from a PHP form before storing it in a MySQL database

My Objective: I aim to utilize a straightforward PHP form to transfer data to a MySQL database. However, in cases where the input includes a specific string, I intend to eliminate it before storing it in the MySQL database. For instance: if the input ...

Can inter-portlet communication be achieved using AJAX?

Is it possible to use an AJAX call in Portlet A to dynamically update Portlet B without refreshing the entire portal page? I am aware that portlets can refresh their content using the JSR286 resourceURL tag, but I am curious about targeting and updating a ...

Tips for parsing a JSON file within my node.js application?

I am working on a node.js service that involves validating JSON data against a schema defined in jsonSchema. Below is the code snippet for my service: app.post('/*', function (req, res) { var isvalid = require('isvalid'); ...

Adjust the text input width appropriately for the cloze exercise

My JavaScript-generated fill-in-the-blank text is causing me trouble when it comes to adjusting the size of the input boxes. Unlike others, I know exactly what the user will or should be entering. If there is a blank space like this _______________, I wa ...

Customizable Designs in Oracle Application Express version 4.2

In my work supporting the organization, I am using APEX 4.2 to create a Training Calendar. While I am not a DBA or programming expert, I have been learning through trial and error. The calendar is already set up, but I am looking for a way to customize ho ...

Showing the unique identifier instead of the actual data in HTML for a Firebase Object using Angularfire

Currently, I am utilizing AngularFire for a specific project. The structure of my firebase Object is as follows: { mainKey: { key1:value1, key2:value2 }, mainkey2: { key3:value3 } } The data has been inputted in a manner tha ...

Executing AngularJS code that returns a promise within an event

In my run function, I am handling the $routeChangeSuccess event. My goal is to use $http to load some data and then change the $template. The issue here is that $http works asynchronously. I have attempted to return a promise inside the event, but it has ...

The HTML body is given a right margin for proper spacing

Within the page, I noticed some margin to the right that extends beyond the body itself, causing a scroll bar to appear at the bottom. However, I'm unable to determine the root cause of this issue. I have provided links to both Codepen and Netlify be ...

Is there a way to deactivate a div in Blazor when clicking outside of the div?

Is it possible to have two divs on a single page, where one appears on the right side and the other on the left side? Is there a way to close or hide the left side div whenever we click on the right side div? ...

Getting the http response content of a Slim PHP API with Angular JS: A step-by-step guide

My Slim PHP programmed API sends JSON responses in the following format: $response['some-text'] = 'blabla'; $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json& ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

Is there a way to automatically position a div element in alignment with an <a> tag within a document?

There is a hidden div element on the page: <div id="data_sprite">Jquery ajax data here</div> The challenge is to align this div with its top right corner when clicking on the first <a> tag at the top of the document, and align it again ...

Guide to forming a JavaScript array from nested JSON data

Looking to parse through an array of objects related to London weather data from the OpenWeatherMap API. How can I create three distinct arrays in JavaScript, each with variable names "dtArray", "tempMinArray", and "tempMaxArray", containing only values f ...

The OK Button Dialogbox is currently malfunctioning

While using jQuery for a dialog box, I encountered an issue when trying to delete an element within it. After clicking the ok button, the dialog box did not redirect or close itself properly. The initial content in the dialog box seems to work fine. < ...

The value of Vue.js props appears as undefined

It appears that I may be misunderstanding how props work, as I am encountering difficulty passing a prop to a component and retrieving its value, since it always shows up as undefined. Route: { path: '/account/:username', name: 'accco ...