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

Position two div elements evenly with text enclosed in a container

I'm looking to incorporate two distinct blocks of text into a container https://i.stack.imgur.com/6mFZK.png Criteria: Text 1: positioned at the top left corner (85% of box size) Text 2: positioned at the bottom right corner (15% of box size) I&ap ...

Passport and Node.js team up to create powerful user group functionalities

Seeking advice on this topic. I am interested in setting up a page with a login form as the main page. Upon logging in, users would be directed to their personalized dashboard. However, if someone logs in with admin privileges, they should be redirected t ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...

Struggling to properly implement an "Errors" Object in the state function of a React Login Form Component

The issue arose while I was following a React tutorial. My objective is to develop a basic social media web application using Firebase, React, MaterialUI, and more. I am currently at around the 5:40:00 mark and have successfully resolved all previous pro ...

Tips on transferring the id value from a modal window to an ajax click event?

I'm having trouble passing the image ID to AJAX for updating it in a modal window. After opening the modal and grabbing the correct ID, I attempt to pass it to AJAX but it shows as undefined. How can I properly pass the ID for further processing? $( ...

Making requests using Axios in a web application created with Express, Node, and EJS

I'm currently working on a project that involves using Express.js, node.js, Axios, and ejs. The aim is to make REST calls to Oracle SQL REST services through Axios. However, I am facing challenges when it comes to dealing with Promises or Async/Await. ...

Update the package.json file by adding a new command to an existing script

Is it possible to automatically run npm install before starting the application with npm start? Here is what my package.json file currently looks like: . . "scripts": { "test": "echo \"Error: no test specified\ ...

Express and Angular2 Webpack integration

Recently, I set up Angular 2 with Webpack and explored its routing capabilities through a sample app. I am now interested in integrating Angular2 for front end routing while utilizing ExpressJS for a RESTful API backend on the same server. For example, ht ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

Exploring AngularJS: Understanding the Differences Between $http's Success and Then

Can someone explain the difference between these methods for me? I am curious about the distinctions between .then and .success functions, as well as .error. Thank you. // Simple GET request example: $http({ method: 'GET', url: '/some ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Background image not displaying

My web page has a background image set using this CSS: body, html { background-image: url(Content/Images/bg-lounge-2-l.jpg); background-repeat: repeat; background-attachment: fixed; /*background-position: 0 -390px;*/ } ...

The express app.get middleware seems to be malfunctioning due to a 'SyntaxError: Unexpected end of input'

Currently, I'm diving into an Express tutorial on YouTube but hit a roadblock with middleware that has left me bewildered. In my primary file, the code looks like this: const express = require('express'); const path = require('path&ap ...

Substitute the temporary text with an actual value in JavaScript/j

Looking to customize my JSP website by duplicating HTML elements and changing their attributes to create a dynamic form. Here is the current JavaScript code snippet I have: function getTemplateHtml(templateType) { <%-- Get current number of element ...

Ways to conceal and reveal content within div elements

I have a code snippet that is currently operational, but I am looking to enhance it by displaying one div at a time. If you would like to view the code, please visit my CodePen link below: https://codepen.io/danongu/pen/YzXvpoJ Due to the extensive amou ...

What is the best way to add child elements to the parent element when the height limit has been reached?

This is the code I've been working on: <ul style="height:200px;width:100%;"> <li>Hi</li> <li>Hi</li> <li>Hi</li> ... (add more items here) </ul> Here is a preview of how it currently looks: ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...