Adjusting the content and style of a div element upon clicking, and restoring the original settings when clicked once more

There is a div with the id #increase-text-weight that displays the text "INCREASE TEXT WEIGHT".

Upon clicking on it, the font weight of another div with the id #post-content should be changed to font-weight: 500 and the text inside #increase-text-weight should be updated to "DECREASE TEXT WEIGHT".

If the text in the div reads "DECREASE TEXT WEIGHT" and you click on it, the font weight of #post-content should then be set to font-weight: 300 and the content of #increase-text-weight should revert back to "INCREASE TEXT WEIGHT".

Is there a way to achieve this?

UPDATE:

I attempted using getElementById but was unsuccessful.

Answer №1

As you embark on your learning journey, here is a concise method using two classes.

To begin, the id selector $('#test') retrieves the node element.

Next, attach a click event listener to the reference. The selector $(this) then refers to the selector used in the attached function, essentially making $(this) equivalent to $("#test").

Using jQuery's .toggleClass() method after the dot allows for adding or removing a class from the element. Additionally, passing a true or false parameter will either add or remove the specified class respectively.

Chaining these two toggleClass() functions will add the class if it's not present or remove it if it already exists.

$("#test").click(function(){ // can also be .on('click',function(){ ... })

    $(this).toggleClass("decreased")
    .toggleClass("increased");

});
.decreased {
  font-weight: 100;
  color: red;
  cursor: pointer;
}

.increased {
  font-weight: 300;
  color: green;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test" class="decreased">Increase my font weight!</div>

Answer №2

If you want a quick solution for this, consider using an if and else statement.

$('#increase-text-weight').on('click', function() {
    if ($(this).text() === 'INCREASE TEXT WEIGHT') {
    $('#post-content').addClass('highlight');
    $(this).text('DECREASE TEXT WEIGHT');
  } else {
    $(this).text('INCREASE TEXT WEIGHT');
    $('#post-content').removeClass('highlight'); 
  }
});

$('#increase-text-weight').on('click', function() {
if ($(this).text() === 'INCREASE TEXT WEIGHT') {
    $('#post-content').addClass('highlight');
    $(this).text('DECREASE TEXT WEIGHT');
  } else {
  $(this).text('INCREASE TEXT WEIGHT');
    $('#post-content').removeClass('highlight'); 
  }
});
div {
  width: 100%;
  height: 100px;
  text-align: center;
  border: 1px solid;
  margin: 0 0 25px 0;
  cursor: pointer;
}

.highlight {
  font-weight: 900;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='increase-text-weight'>INCREASE TEXT WEIGHT</div>
<div id='post-content'>Text text and text</div>

Answer №3

To change the appearance of a div element when clicked, you can use an onClick event. Every time the div is clicked, it checks its associated class and makes modifications accordingly. For instance, updating the text content within the div using `.text()`, and toggling between classes like this:

var myDiv = $("#test");

myDiv.click(function() {
  if (myDiv.hasClass("decreased")) {
    myDiv.removeClass("decreased")
      .addClass("increased")
      .text("Decrease my font weight!")
  } else {
    myDiv.removeClass("increased")
      .addClass("decreased")
      .text("Increase my font weight!")
  }
});
.decreased {
  font-weight: 100;
  color: red;
  cursor: pointer;
}

.increased {
  font-weight: 300;
  color: green;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test" class="decreased">Increase my font weight!</div>

Alternatively, you can achieve this using pure JavaScript in the following way:

var myDiv = document.getElementById("test");

myDiv.addEventListener("click", function() {
  if (myDiv.className === "decreased") {
    myDiv.classList.remove("decreased");
    myDiv.className = "increased";
    myDiv.textContent = "Decrease my font weight!";
  } else {
    myDiv.classList.remove("increased");
    myDiv.className = "decreased";
    myDiv.textContent = "Increase my font weight!";
  }
});

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

As I scroll past the top or bottom of the page, the body's background color transitions to a new shade

I am encountering an issue with my next.js app where the body background color is set to black. Here is the code in globals.css: body { background-color: black; padding: 0; margin: 0; font-family: 'Titillium Web', sans-serif; } However, ...

incorrect encoding of Greek characters due to the multer upload package

When uploading files with Greek characters, the uploaded titles are saved as ΠÏξ Îαξ & ÎαÏÏιμιÏαίοι Here is the code for multer variables inside a js file: const storage = multer.diskStorage({ destination: f ...

Efficiently handling multiple responses in Express.js per single request

Currently exploring Node.js and working on a bot utilizing Dialogflow. I am aiming to establish a straightforward process: Step 1: Dialogflow sends a POST request with parameter param1 Step 2: My application replies with a waiting message (e.g., "your re ...

Strange spacing issues with inline-block elements and struggling to vertically center content within them

I feel like I'm losing my mind trying to figure this out... any help would be greatly appreciated. There are three divs on the page that need to sit on a single line. They must be square with rounded corners, so setting width and height is necessary ...

What steps can be taken to ensure that the content in column two does not impact the positioning of content in column one?

Is there a way for the input text container to remain in its original position within the layout even after submitting text? Usually, when the data displayed container's height increases, it pushes the input text container down. Despite trying absolu ...

jQuery mobile enhancing user experience with dynamic background images

I am having trouble setting different background images for each page in jQuery Mobile. <div data-role="page" id="pageone">... </div> <div data-role="page" id="pagetwo">... </div> Since each page has a unique ID, I tried ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

What is the best way to transform a string into React components that can be displayed on the screen?

Stored in my database are strings that contain partial HTML content, as shown below: “Intro<br /><br />Paragraph 1<br /><br />Paragraph 2” If I want to display this string within a new <p> element, what is a straightforwa ...

Trouble arises with Pagination feature of Mui Data Table

Currently, I am working on a project that involves retrieving data from the CoinMarketCap API and presenting it in an MUI Data Table (specifically a StickyHeader Data Table). However, I have been encountering difficulties with changing the color of the tex ...

Understanding the Code for Responsive Web Typography with line-height in ems

I am currently trying to delve into the CSS calculation process behind the styling in the code snippet provided. This code snippet is from a responsive WordPress theme, and I am struggling to decipher how the em values for the line-height of the <h> ...

Ways to collect email address or name from an email message

Suppose I send an email to someone with a link at the bottom. The text of the link might be something like click me. When the user clicks on this link, they will be directed to a webpage. On this webpage, a message saying "Thank you" will be displayed a ...

Navigate to a specific moment in an HTML5 audio track by clicking on the progress bar

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var counter = 0; ...

Scrolling triggers events

I am currently working on getting code to execute when the scroll bar reaches a certain point on my page, specifically halfway down the page or at 500px. The challenge I'm facing is that the code works fine for triggering the event when scrolling to t ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

How can the useEffect Hook be utilized to perform a specific operation just one time?

My goal was to have a modal popup appear if the user moves their cursor outside of the window. I experimented with the following code: React.useEffect(() => { const popupWhenLeave = (event) => { if ( event.clientY <= 0 || ...

Is it possible to choose an element directly without having to trace back to the parent element first?

My goal is to target the class this and then access that without having to go through the parent tr element. This snippet shows my HTML structure: <tr> <td> <div>some content</div> <select class="this"> ...

Is it possible to use an onclick function to input JavaScript values into a password entry box seamlessly?

Is there a way to input password values continuously using a JavaScript onclick function into a password field? I have two images, one 'Blue' and one 'Red', that trigger an onclick function with the following values: Blue= w3! Red= T4 ...

How can states be passed down as props in React?

This might be a beginner question, but I've been struggling with it all day. Any help would be appreciated. Apologies for the length, I just wanted to explain everything I'm having trouble with I am attempting to create custom buttons by build ...

Arrange the select default option using AngularJS as the first option

I've been working on a project using Angular where I fetch data from a JSON file and push it to an array object. This data is then displayed in the options of a select element. My issue is: The default option with selection appears first, but I only ...

What is the most efficient way to incorporate MongoDB into your codebase using ES6-style

I have encountered an issue with importing MongoDB using the es6 import-from style. When I try to import using node's require method, everything works fine. let mongo = require('mongodb'); let MongoClient = mongo.MongoClient; However, when ...