Unable to clear input code as intended

After using the code I found here, it seemed to work as expected. However, when implemented on my page, everything worked except for the cursor not changing when hovering over the 'x' button. Surprisingly, the cursor only changed when the input box was disabled.

Furthermore, an observation I made was that the code wouldn't function unless I added the following snippet to my CSS file. Not sure if this is relevant...

.ui-autocomplete{}

My theory is that it might be related to bringing the image to the front, but all attempts to fix it have proved futile.

Update: Included screenshots showcasing the issue...

Cursor changes when input is disabled...https://i.sstatic.net/qa7SX.png

Cursor doesn't change when enabled...https://i.sstatic.net/9fstm.png

The main goal is to modify the cursor to a hand when the input is enabled.

Here's an update to the code... still facing issues but wanted to share the revised version.

$(function($){
    function tog(v){return v?'addClass':'removeClass';} 
    $(document).on('mouseenter', '.clearable', function(){
        if ($(this).prop('disabled')===false) {
            $(this)[tog(this.value)]('x');
        }
    }).on('mousemove', '.x', function(e){
        $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');
    }).on('mouseleave', '.x', function(){
        $(this).removeClass('x');//.val('').change();
    }).on('click', '.onX', function(ev){
        ev.preventDefault();
        $(this).removeClass('x onX').val('').change();
        $(this).trigger('keyup');
    });
});

Answer №1

Creating a jQuery widget from functional code...

(function($, undefined) {       
    $.widget("myplugin.clearmojo", {
        version: "1.0",

        _create: function(){
            $('input[type=text]').addClass('clearable');

            this.element
                .on('mouseenter', function(){
                    if ($(this).prop('disabled')===false && $(this).val()!='' && $(this).prop('readonly')===false){
                        $(this).toggleClass('x');
                    };
                })
                .on('mousemove', function(event){
                    if ($(this).prop('disabled')===false && $(this).val()!='' && $(this).prop('readonly')===false){
                        $(this).toggleClass('onX', this.offsetWidth-18 < event.clientX-this.getBoundingClientRect().left);
                    };
                })
                .on('mouseleave', function(){
                    $(this).removeClass('x');
                })
                .on('click', function(event){
                    var elementOffsetWidth=this.offsetWidth
                    var parentOffset=$(this).parent().offset();
                    var relativeX=event.pageX-parentOffset.left;
                    var xOffset=elementOffsetWidth-16

                    if ($(this).prop('disabled')===false && $(this).val()!='' && $(this).prop('readonly')===false && relativeX>xOffset){
                        event.preventDefault();
                        $(this).removeClass('x onX').val('').change();
                        $(this).trigger('keyup');
                    };
                });           
             },         
        });
}(jQuery));

CSS styling:

input[type=text]::-ms-clear{
    display: none;
}

.clearable{
    background: #fff url('../images/delete.jpg') no-repeat right -10px center;
    background-size: 10px 8px;
    padding: 0px 0px 0px 0px; 
    transition: background 0.4s;
}

.clearable.x{
    background-position: right 3px center;
}

.clearable.onX{
    cursor: pointer;
}

Usage example:

$("input[type=text]").clearmojo()

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

Injecting dependencies in AngularJS when utilizing the controller-as syntax: A how-to guide

As I dive into the controller-as feature outlined in the documentation, I'm refining one of my controllers to align with their recommended syntax. However, I'm facing a challenge when it comes to injecting the $http service into my search() funct ...

Centered styled checkbox cannot be checked with TalkBack or VoiceOver enabled

I am currently testing the accessibility of a mobile web app I developed and have encountered an issue with checkboxes while using TalkBack on Android or VoiceOver on iOS. The problem arises from hiding the actual checkbox and presenting a styled label th ...

What is the most effective method for developing HTML with PHP or Jquery?

My JavaScript Object contains some important information that I need to display. I have two possible options for generating the HTML from this object. I am unsure which method is the most appropriate, or if it is simply a matter of personal preference. 1 ...

The color of active links in TailwindCSS remains unchanged

In my project, I am using NextJS along with Tailwind CSS to create a top navigation bar. My goal is to change the text color for active links within the navigation bar. Below is the code snippet I have implemented: const Header = () => { return( ...

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

Total quantity based on user input

Recently embarking on my Vue journey, I'm curious about how to implement a feature where the input data takes a number and displays it in a variable. Additionally, if the number is entered twice, I want to add them up. <template> ... </te ...

Difficulty encountered when trying to obtain div height automatically

For a while now, I've been attempting to dynamically determine the height of an image as the browser window is adjusted. Despite using console.log() to verify my results, I keep getting a value of 0. What could be causing this discrepancy? $(functio ...

java script loop - how to save index values

Planning to create a program that extracts the domain from an email address. How can this be done without using built-in functions like .map .filter .reduce .split .join .indexOf .findIndex .substring? Many online sources suggest using a for loop to locat ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

How to use Selenium-Webdriver (Java Script) to wait for an element to vanish

driver.wait(until.elementIsNotVisible(By.css(".popup-backdrop fade")), 15000); Is there a way to wait for the ".popup-backdrop fade" overlay to disappear before proceeding with element click? I am working with Selenium-webdriver using JavaScript, not Jav ...

When you open the link in a new tab, the form submission does not occur

I am currently working on a form that includes a JavaScript submit function. Within the form, there are 3 anchor tags that I want to use to set different values to a hidden parameter when submitted based on the link clicked. Although the form submission w ...

Viewing YouTube videos on an iPhone can be done through a web view

I am having some trouble playing videos in this specific format. http://www.youtube.com/embed/lNOMZoF9VlM?rel=0 Here is my HTML string. NSString *html = [NSString stringWithFormat:@"<html><head>\ <body s ...

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

Exploring the Angular search scope for data

I am working on creating a function that will search my scope for the value of status and return true if it matches 1. Below is the array I am using for this task: "review": { "currentStep": 7, "stepA": { "status": 0, }, "stepB": { ...

Position the div at the bottom of the screen rather than at the bottom of its parent element

One of my HTML structures imitates an app layout with pages. To understand the issue, please take a look at the JsFiddle link first. .screen-emulator { width: 300px; height: 400px; background-color: red; } .head { width: 100%; height: 70px; ...

The versatility of reusable Backbone components

As I search for the best way to ensure the reusability of Backbone views, I have come across various solutions but am unsure which one would best meet my needs. My goal is to create multiple widgets populated with real-time data and I require a base compon ...

Manipulate database variables using Javascript

As a beginner in JavaScript, I am seeking assistance with some tasks. I have to save a simple number as a JavaScript variable into a database and display the current value on two websites (with PHP used to retrieve it on the second site). This is my curre ...

CSS: Setting the minimum width of a table in your web design

I am facing an issue with a table that should expand to fill 100% of the width, but also need it to respect a min-width rule when I resize my browser window. Unfortunately, setting a min-width directly on the table does not seem to work (tested in Safari&a ...

Looking to eliminate the pesky mystery padding that's wedged between the background and border

Can anyone assist with getting rid of the mysterious padding that appears between a border and its background? The design looks perfect in the preview, but when exported, there is unwanted padding inside the frame. Here's the snippet of code: < ...

Newbie in JavaScript baffled by typical testing protocol

Hello everyone, I've always been someone who just writes code, runs it, and fixes bugs as they come up. But now that I'm working on a medium-sized project with a team, I realize the importance of proper JavaScript testing. So here's my que ...