Watermarked Input (styled with css and enhanced with Jquery)

JavaScript

$(document).ready(function () {
    $(":input[data-watermark]").each(function () {
        $(this).val($(this).attr("data-watermark"));
        $(this).bind('focus', function () {
            if ($(this).val() == $(this).attr("data-watermark")) $(this).val('');
        });
        $(this).bind('blur', function () {
            if ($(this).val() == '') $(this).val($(this).attr("data-watermark"));
            $(this).css('color','#a8a8a8');
        });
    });
});

HTML

<label>Name: </label>
<input class="input" type="text" name="name" maxlength="" data-watermark="My Name" />

CSS

.input{
    width:190px;
    height:16px;
    padding-top:2px;
    padding-left:6px;
    color:#000;
    font-size: 0.688em;
    border:#8c9cad 1px solid;
}

To improve this code, I want to ensure that when the watermark text is in the input field, the text color should be gray (#a8a8a8). When the user enters their own text, the color should shift to black.

This code snippet can also be found on this fiddle: http://jsfiddle.net/qGvAf/

Answer №1

The feature you are looking for, known as "Input with Watermark," already exists and is called the placeholder attribute. This functionality is supported in modern browsers, as seen here.

If you need to support older browsers, you can utilize a jQuery plugin to simulate the placeholder behavior.

To customize the color of the placeholder text, you can use CSS similar to the following:

.placeholder {
    color: #a8a8a8;
}
::-webkit-input-placeholder {
    color: #a8a8a8;
}
:-moz-placeholder {
    color: #a8a8a8;
}

Unfortunately, it is not possible to combine these rules for different browsers; as discussed here, it will not work.

Answer №2

$(document).ready(function () {
    $(":input[data-watermark]").each(function () {
        $(this).val($(this).attr("data-watermark"));
        $(this).css("color","#a8a8a8");
        $(this).bind("focus", function () {
            if ($(this).val() == $(this).attr("data-watermark")) $(this).val('');
            $(this).css("color","#000000");
        });
        $(this).bind("blur", function () {
            if ($(this).val() == '') 
            {
                $(this).val($(this).attr("data-watermark"));
                $(this).css("color","#a8a8a8");
            }
            else
            {
                $(this).css("color","#000000");
            }
        });
    });
});

Answer №3

Do not overwrite existing values

I encountered a minor issue with this great solution, but I made a small adjustment to resolve it. I wanted to share the fix.

Simply include the if statement on line 3 to prevent overwriting loaded values.

$(document).ready(function () {
    $('.watermark').each(function () {
    // insert the following line
        if (this.value == '') {
            $(this).val($(this).attr("data-watermark"));
            $(this).css("color", "#a8a8a8");
            $(this).bind("focus", function () {
                if ($(this).val() == $(this).attr("data-watermark"))         
                    $(this).val('');
                $(this).css("color", "#000000");
            });
            $(this).bind("blur", function () {
                if ($(this).val() == '') {
                    $(this).val($(this).attr("data-watermark"));
                    $(this).css("color", "#a8a8a8");
                }
                else {
                    $(this).css("color", "#000000");
                }
            });
    // Do not forget to close the bracket
        }
    })
});

I hope you find this helpful.

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 jQuery script is compatible with all web browsers when offline and online, with the exception of Chrome when

Hi there, I've encountered a strange issue: Could you take a look at this newly uploaded page: On the page, there is a dropdown menu with various options (best viewed in Firefox or Safari). When users select a specific option, all other instances a ...

Updating the background color and adjusting the text input color in the upcoming user interface

import {Input} from "@nextui-org/react"; <Input label="Email" radius='sm' /> https://i.sstatic.net/gprRpEIz.png I am looking for a way to customize the input text color and the label color separatel ...

"Automatically Saving Recorded Audio Files on a Server in ASP.NET MVC 4: A Step-by-Step

I'm currently working on a project using ASP.NET MVC 4. I've implemented recorder.js to record audio, and it works perfectly in chrome. When the user clicks the download link, the recorded audio file is downloaded to their local machine in the D ...

Having difficulty configuring particlesJS as the background

If you're looking to create a three-page single scrolling webpage with particlesJS as the background, consider using the following resources: particlesJS Website and particlesJS Github Page. An issue arises when trying to set particlesJS as the back ...

Is it Possible for TD Not to Function as a Hyperlink?

I've exhausted all topics but nothing seems to be working for me! My goal is to have a table completely covered with anchor tags, but for some reason, it's not displaying any links within the TD elements, not even the text! HTML <tab ...

Is it possible to eliminate jagged edges in CSS 2D rasterization by applying anti-aliasing to subpixels?

It appears that the HTML/CSS engine automatically rounds values to the nearest whole px unit. It would be interesting to see non-discrete sizing options (floats). A closer look reveals that in Chrome, widths/heights are rounded to the nearest physical pix ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

Retrieving input values seamlessly through Jquery Ajax without the need for manual clicking or server intervention

I have encountered a challenge. I am familiar with using jQuery selectors to retrieve input values and update information after a button click. However, I am curious if it is possible to dynamically update the information as users input values into a form, ...

Switch up the background image of the <li> element when the <a> tag is clicked

html: <ul> <li id="Co" class="libgc" ><b>CO</b></li> <li id="NSCO" class="libgc active"><span> <a href="#NSale.php" target="homeFrame" class="aclass">NSale</a></span></li> </ul ...

Tips for ensuring a functioning dropdown menu while maintaining a fixed navigation bar position

I am facing an issue with my navigation bar. I have set the position to fixed to keep it at the top, but this is causing the drop-down functionality to stop working. Please advise on where I should move the position fixed property so that my nav bar remai ...

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Manipulating the display style of an element without using jQuery

Could anyone assist me with this issue? I am currently facing a challenge in making the following script functional. It is intended to hide the button after it has been clicked. The script is being called through Ajax and PHP, so I am unable to utilize jQ ...

Currently, I am experimenting with creating interactive tabs by utilizing jQuery

Does anyone have suggestions on how to create clickable tags using JavaScript without causing everything to disappear when clicking on the tabs? Here is the HTML code: <div id="contentwrap" class="round"> <h1>About Eclipse</h1> ...

What is the best way to align the last two items at the bottom of the screen?

Incorporating kendo controls and aiming to align the split button and button at the bottom of the div, I'm encountering difficulties achieving this. How can I eliminate the top gap? Even with attempts like setting margin-top and padding-top as 0, the ...

Differences between CSS Display None and Collapse

Can you explain the distinction between the following two options? display: none; visibility: hidden; I always thought that visibility: collapse was only applicable to tables. Am I mistaken? ...

Is there a way to reload or refresh an IFrame without causing a white flash?

My website includes an iFrame that loads a variety of pages. Initially, I hide the iFrame until the content is fully loaded, at which point I display it. However, I now have some pages that require a postback to retrieve information from the database based ...

equal child width as parent column container

I'm in the process of developing a custom dropdown search bar that presents results as the user enters text. One issue I'm facing is that the list of results must have a position: absolute. This causes it to disregard the width of the parent col ...

Verify the existence of a random entry in the database prior to insertion

After creating a code generator that provides various types of codes, I want to simplify it. When a user submits a registration form, certain information is collected and a random code is generated for them. However, I need this random code to be unique to ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Display a single video on an HTML page in sequential order

My webpage contains a video tag for playing online videos. Instead of just one, I have utilized two video tags. However, when attempting to play both videos simultaneously, they end up playing at the same time. I am seeking a solution where if I start pla ...