if the input field is empty, eliminate the class

Within the code snippet, a function is present which performs the following actions.

  • It searches for an email in the input field, then converts the email to an md5 hash, and finally generates a Gravatar URL that is inserted into a class using fadeIn();

    $(document).ready(function(){
    
        $('.email').on('change', function(){
            var hash = hex_md5($('.email').val()); 
            $('.gravatar').attr('src', 'http://www.gravatar.com/avatar/' + hash + '?s=120').addClass('gravatar-glow').fadeIn("slow");
        });
    });
    
    
    HTML Part: <img src="" class="gravatar" style="display: none;"/>
    

The issue at hand

  • If the email is removed from the input field, the class still remains visible but now displaying the default Gravatar image instead of the md5 hashed one.

The desired outcome is to hide the previously used class when the input field is empty, such as when a user decides to delete their email to use a different one, rather than showing the Default Gravatar image.

Below is the jQuery code implementation:

Answer №1

If you want to dynamically add or remove a class based on a condition, you can leverage the toggleClass method in jQuery. This function takes a boolean value as its second parameter - if this value is true, it adds the specified class, otherwise it removes it.

.toggleClass( className, switch )

In the code snippet below, we have an event listener attached to the change event of an input field with the class "email". When the input value changes, we calculate a hash using the MD5 algorithm and update the image source accordingly. The toggleClass method is used to toggle the ".gravatar" class based on the length of the input value.

$('.email').on('change', function(){
    var val = $.trim(this.value), hash = hex_md5(val); 
    $('#element').prop('src', function(){
         return val.length
                ? 'http://www.gravatar.com/avatar/' + hash + '?s=120'
                : 'default path to the image'
    }).toggleClass('.gravatar', val.length)
      .fadeIn("slow");
});

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

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Occasionally, the function `Element.getElementByTag("mytag")` may come up empty

Here is the outer html of Element1 in CKeditor: <element1 id="s1"> <mytag>Test1</mytag> <span> </span> Some text <mytag>Test</mytag> <span> </span> <mytag>Test3</mytag> some text <span&g ...

Utilizing JQuery, Ajax, and a Struts2 framework to manage and display

I am in need of assistance in implementing a JQuery/Ajax call to retrieve a List from a Struts action and populate a DIV with the list elements using s:iterator. Below is the JQuery code snippet I have: function lookupCustomerJs() { alert("lets s ...

"Revamp the appearance of the div element upon clicking elsewhere on the

function replace( hide, show ) { document.getElementById(hide).style.display="none"; document.getElementById(show).style.display="flex"; } @import url('https://fonts.googleapis.com/css2?family=Allerta+Stenci ...

Storing JavaScript arrays in CSV format on the server

I am currently facing an issue while trying to save a multidimensional Javascript array as a CSV file on the server. Despite my efforts, the CSV file created does not seem to contain the actual array data, and I am unsure of what is causing this discrepanc ...

What is the process for including id parameters within the URL of an HTML page?

As I work on building a website with ReactJS and webpack, I encounter the need to access URL parameters. One specific challenge I face is creating a universal blog post view page that can be dynamically loaded based on the blog id parameter in the URL. Rat ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Is it possible to apply styling to an element based on the position property of its ancestors using only CSS?

Wondering if it's possible to style an element based on its ancestors' CSS property value. Consider the HTML snippet below: <div><!-- ancestor --> <!-- Any number of descendant levels before reaching the target div --> < ...

Use a for loop to iterate through elements and retrieve input values using getElementById()

As I work through a for loop in JavaScript, I am utilizing the getElementById() method to fetch multiple input values. To begin, I dynamically created various input boxes and assigned distinct id's using a for loop. Subsequently, I am employing anoth ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

Could anyone assist me in positioning my personalized Context Menu beside my cursor?

If possible, I would appreciate some assistance with my custom context menu. It may require some minor tweaks or a fresh idea on how to address the issue. Ideally, I would like to keep the HTML and CSS somewhat unchanged. [I'm not sure what to write ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Display personalized error messages using jQuery and PHP

I implemented an Ajax autocomplete feature on an input field within a form using jQuery. Here are the ajax settings I have set up: $.ajax({ type: "POST", url: myUrl, data: $("#id__form").serialize(), success: function(data){ ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

Is it possible to determine if a web page is designed for a personal computer or a

Is there a way to identify whether a given URL is intended for PC or mobile devices? I have a collection of URLs, and I need to determine if each one corresponds to a PC or mobile version. Is there any specific HTML element or marker within the page sour ...

Modifying the Placeholder Color in a Material UI Autocomplete: Tips and Tricks

In my team, we are working on two projects that both utilize an internal library with a header containing a search box. In one project, the placeholder text "Search" displays normally. https://i.stack.imgur.com/lhL5V.png However, in the second project wh ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Watch the video and follow along with your mouse using jQuery

Wouldn't it be cool to have a video play and follow your mouse pointer when you hover over the red box? And then once you move away, the video stops and disappears. Check out my progress so far: jsfiddle Here's the jQuery code I've used: $ ...

What is the best way to split a div diagonally while keeping the border unchanged?

I'm attempting to devise the design displayed in the link below: I have experimented with the following code: .App { font-family: sans-serif; text-align: center; } #container { height: 300px; width: 300px; overflow: hidden; backgrou ...