Unable to adjust the color of the font

I am trying to create a toggle effect for the colors of a fontawesome icon when clicking on a text link, but it only works with a button. Here is the HTML code snippet:

<div class='post'>
    <i class='fas fa-heart' id='h2' style='color:red'></i>
    <span>
        <a href='' class='like' bid='2' cid='h2'>like</a>
    </span>
</div>
<br>
<br>
<button>click</button>

Here is the working JavaScript part:

var bac=document.querySelector("button");
bac.addEventListener("click", function(){
  if (document.getElementById('h2').style.color=="red"){
    document.getElementById('h2').style.color="purple";
  }else if(document.getElementById('h2').style.color=="purple"){
    document.getElementById('h2').style.color="red";
  }
});

Unfortunately, the following section does not work as expected (I want to use this because I need to add an AJAX call):

<script type="text/javascript">
        $(document).ready(function(){
            $('.like').click(function(){
                var cid = $(this).attr('cid');
                if (document.getElementById('h2').style.color=="red"){
                    document.getElementById('h2').style.color="purple";
                }else if(document.getElementById('h2').style.color=="purple"){
                    document.getElementById('h2').style.color="red";
                }
            });
        });
      </script>

Answer №1

For this to work properly, you need to incorporate preventDefault() into your click() function.

    $(document).ready(function() {
      $('.like').click(function(e) {
        e.preventDefault();
        var cid = $(this).attr('cid');
        if (document.getElementById('h2').style.color == "red") {
          document.getElementById('h2').style.color = "purple";
        } else if (document.getElementById('h2').style.color == "purple") {
          document.getElementById('h2').style.color = "red";
        }
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='post'><i class='fas fa-heart' id='h2' style='color:red'>test</i><span><a href='' class='like' bid='2' cid='h2'>like</a></span></div><br><br><button>click</button>

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

How to customize the color of radio buttons in JFXRadioButton using CSS

I am facing an issue with customizing the styling of JFXRadioButton component from this library : jfoenix.com I want to modify the color of the circle, but the default class is not working. Are there any suggestions or solutions available? (The colors me ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

Unexpected Timed Out error from Socket.IO adapter when MongoDB connection is lost

I have been experimenting with capturing the disconnection event in mongodb. Everything is working smoothly with this setup: simple.js 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:2701 ...

How can Components access variables declared in a custom Vue.js plugin?

I had developed a unique Vue js plugin to manage global variables as shown below: CustomConstants.js file: import Vue from 'vue' export default { install(Vue){ Vue.CustomConstants = { APP_VERSION: '2.1.0' ...

What is the best way to share in a LinkedIn group using JavaScript?

Attempting to share on my group via the JavaScript API is resulting in an error - Access to write groups denied (403 Forbidden). How can I resolve this issue? IN.API.Raw("/groups/" + 10356772 + "/posts?format=json") .method("POST") .body(JSON.stringif ...

Utilizing jQuery's multiple pseudo selectors with the descendant combinator to target specific elements

My code includes the following: <div class="a"><img></div> and <div class="b"><img></div> I want to dynamically enclose img tags with a div and utilize $(":not('.a, .b) > img") for ...

Want to display a button depending on the page you are navigating from in Ionic?

My home page displays a list of items, and whenever I add a new item, I want it to return to the home page. However, if I navigate back to the root from the addItemPage, I also want to display a button for saving the list and making an HTTP call. I'm ...

Guide to incorporating a page separator in between each page refresh with Jquery's Infinite-scroll

Looking to enhance my website by adding additional content with each page load using Jquery Infinite-scroll. For instance, I envision placing a mini-footer featuring some useful links after the first page. This could serve as a visual break between pages. ...

How can ReactJS retrieve URLs from a database to upload images?

Hey everyone, I'm relatively new to ReactJS and nodeJS for frontend and backend development. Recently, I received some assistance in displaying all the outputs of a table in a select form, but now I'm facing difficulties with images. My colleagu ...

Issue with dynamic elements created through Ajax and toggleClass() in .each() loop

After a successful call to .ajax(), I am generating a series of div's containing forecasted weather data. My goal is to initially display only the div with class="forecast-list", and then listen for the user's click on that element to reveal addi ...

Effortlessly disable and remove values from checkboxes using Vue

I am working with a group of checkboxes, each with its own model. These checkboxes need to be enabled or disabled based on the state of a master checkbox. Enabling and disabling them is simple, as I just need to include :disabled="!MasterCheckbox" in each ...

Instructions for populating a DataTable with JSON data while allowing for editing of rows

Hey there, looking for some expert advice, I've been experimenting with the datatable plugin and I'm curious if it's feasible to populate a table with row editing actions using ajax? This is the code snippet I currently have. It successfull ...

Error: The login is invalid due to authentication failure with code 535 5.0.0

I'm currently working on setting up Outlook calendar events by integrating a mailing service with my project. I'm using the Express framework and Mongoose queries for this purpose. Below is the code snippet I have implemented: var _ = require(& ...

Ways to determine the visibility status of an HTML tag in Angular 2

Is there a way to check if a div is hidden in Angular 2? ...

Uploading Files in Django Using Ajax Without a Form

As I explore using Valum's Ajax Upload for file uploads on my Django-based website, I am faced with a challenge. Currently, I am avoiding a traditional form because AU sends the entire upload as POST data in an AJAX request. My current approach involv ...

The content on the page is not visible when viewing on an Android device in

After spending a considerable amount of time browsing StackOverFlow for coding solutions, I have come across a problem that I can't seem to find an answer for. Yesterday, I made some changes to the media queries on my site in order to incorporate a dr ...

regex for extracting a hyperlink tag from an HTML snippet in a server-side environment

On the server-side, I have an HTML page source stored as a string. My goal is to extract <link rel="icons"... elements from the string and store them in an array. There may be multiple <link rel="icons"... elements with the same starting tag, and I ...

Incorporating Files from Varied Folders

So I have these files: require_once("includes/database.php"); This poses a problem when the file is included from shopping_cart.php because the path makes sense in that context. But if the table.php file is called directly, the current directory will be ...

receiving ajax server updates

As a beginner in the world of ajax and wanting to receive constant updates from the server, I have been researching different methods to achieve this. However, I am unsure if my approach will work and would like some feedback on my understanding of the pro ...

The inconsistency in div sizes may be attributed to the line-height setting

I'm trying to get two divs to sit next to each other and be aligned at the bottom. However, when I add a button and set the line-height, it drops slightly. See examples with images below. My Desired Layout: https://i.sstatic.net/MZQvg.png Current I ...