Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled?

For example, if the title is set to

<i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true">
within <div class="postoption">

I would like to toggle both the title text and its class using the following code:

$('.postoption').click(function(){
    $(this).find('i').toggleClass('fa-star-o fa-star');
    $(this).find('i').toggleTitle('Favorite This Post *OR* Remove Favorite')
});

Answer №1

To add or remove favorite functionality, you can implement the following code snippet:

var starIcon = $(this).find('i');

if (starIcon.attr('title') === "Unfavorite") {
    starIcon.attr('title', "Favorite");
} else {
    starIcon.attr('title', "Unfavorite");
}

I hope this solution works for you!

$('.favorite-btn').click(function() {
  $(this).find('i').toggleClass('fa-heart-o fa-heart');

  var target = $(this).find('i');

  if (target.attr('title') == "Unfavorite") {
    target.attr('title', "Favorite");
  } else {
    target.attr('title', "Unfavorite");
  }
});
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="favorite-btn">
  <i title="Favorite" class="far fa-heart" aria-hidden="true"></i>
</div>

Answer №2

Retrieve the title value using attr() and then toggle it.

$('.postoption').click(function() {
  $(this).find('i').toggleClass('fa-star-o fa-star');
  var title = $(this).find('i');
 //check the value of title and switch it
 console.log(title.attr("title"));
 if(title.attr("title") === "Favorite This Post"){
    title.attr("title", "Remove This Post");
 }
 else{
  title.attr("title", "Favorite This Post");
 }

});
.postoption{
  background: #ccc;
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="postoption">
  <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true">Icon</i>
</div>

Answer №3

An Alternative to Jquery

<!DOCTYPE html>
<html>
<body>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<i id='iTag' class="red" title="Favorite This Post"></i>
<button id="toggleButton" type="button"> Toggle title</button>

<script type="text/javascript">

 document.getElementById('toggleButton').onclick = function(){
    var iTag = document.getElementById('iTag'),
        iTagTitle = iTag.getAttribute('title');

    if(iTagTitle == 'Favorite This Post') {
        iTag.setAttribute('title','Remove This Post');      
    }
    else {
        iTag.setAttribute('title','Favorite This Post');        
    }   
 };

</script>
</body>
</html>

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 property 'push' cannot be read because it is undefined

$scope.AddTask = function () { $scope.tasks.push([{ "taskName": $scope.taskName, "priority": $scope.selectedP }]); }; $scope.tasks = [{ "taskId": 1, "taskName": "task 1", "priority": 1 }, { "taskId": 2, "taskName ...

Adjust the parent container to perfectly accommodate the child element

Is there a way to resize the container box to fit its dynamic content without using JavaScript? Here is the sample code for the problem: <div id="container"> <div id="content"></div> </div> #container { position: relativ ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

The process of altering a grid in HTML and adding color to a single square

I am facing a challenge that I can't seem to overcome. I need to create a game using HTML, CSS, and JS. The concept involves a grid where upon entering a number into a text box, a picture of a cartoon character is displayed in a square which turns gre ...

React's useEffect delay instability

Currently, I am in the process of creating a Pomodoro clock. My approach involves utilizing the useEffect and setTimeout functions to develop countdowns. Initially, everything appeared to be running smoothly until I noticed a delay ranging from 30ms to 50m ...

Tips for Maintaining Hidden Side Navigation Bar on Postback in C# Web Forms Application

I built a C# web application using webforms, complete with a side navigation bar that is displayed by default. However, when the user clicks on a toggle button, it gets hidden and will be shown again upon another click. Here is the JavaScript code in my s ...

Hiding content with a fixed Bootstrap menu

How can I prevent the fixed menu in my web page from hiding content, especially when the screen size is reduced and responsive menu hides even more content? Here's an example of the code: <nav class="navbar navbar-inverse navbar-fixed-top" styl ...

obtaining the data stored in the backing bean and showcasing it upon submitting the form

I currently have an a4j:commandbutton implemented on my jsf page. Here is the code snippet- <a4j:commandButton id="submitBtn" value="#{msgsMass.MM_04_02_BTN_CONTINUE}" reRender="addNewCardForm,saveAddNewCardForm" immediate="true" action="#{bBea ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

There appears to be an issue with the functionality of the external CSS pathway

placeholder image hereplaceholder image hereplaceholder image here I'm encountering a problem and struggling to identify the mistake in my current approach. ...

The Art of HTML and CSS Layouts

My code is displaying a layout where the 'Login or Signup' link is not aligning to the right side of the page as intended. Can anyone help me with this issue? HTML <header> <h1>Heading</h1> <p>A clean, minimal, gri ...

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

The input field malfunctioned after the clear button was pressed

Hi there, I have a question. Every time I try to click on the clear button, it keeps giving me an error message and I'm not sure what the issue is. Also, I can't type in the field anymore after clicking it. methods: { add () { this.ta ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

Reloading content using AJAX

Index.php ... <form id="calculator_form" name="form" action="" method="get" > <input name="one" type="text"> <input name="two" type="text"> <input type="submit"> </form> ... <!-- reload area --> <?php if(isset( ...

fetch and parse JSON data using jQuery

I am currently developing a basic chatbox using Zend Framework and JQuery. I am using $('#outputArea') to load the content, which is essentially a div with $.load(). However, the response I get is a JSON object with multiple messages that I need ...

A single object that can be dragged and dropped onto two separate destinations, with one of the destinations also

After researching extensively on various platforms, I have been unable to find a solution that effectively addresses my specific issue. Currently, I have two div elements functioning as droppable containers. The first div, #imgBrowser, is populated with i ...

The request was blocked due to cross-origin restrictions as the CORS header 'Access-Control-Allow-Origin' was found to be missing

I encountered an error while working with AngularJS. The error message reads: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header 'Access-Control-Allow-Origin' missing). Below i ...

Issue with applying CSS properties of 'top' and 'left' to a dynamically created div using

After an extensive search on both the site and the internet, I have not had any luck so far. I am dealing with a series of dynamically-generated divs using JQuery, cloned from the original HTML source. While I can manipulate the positioning properties of ...