0

I have created a javascript function like the following:

function highlight_input() {
  $("input").css("background", "yellow");
}

$("#input1").highlight_input();
$("#input2").highlight_input();

Now I want to highlight the two input types when need! but both should not be highlighted at a time!

1
  • 2
    Please explain what you're trying to do more clearly. What do you mean "when you need"? Commented Feb 9, 2017 at 7:17

2 Answers 2

5

You can create a basic plugin by adding function to jQuery.fn(extending jQuery prototype), where this refers to the jQuery object inside the function.

jQuery.fn.highlight_input = function() {
  // here this refers to the jQuery object , so 
  // you can apply jQuery methods without wrapping
  this.css("background", "yellow");
  // return the object reference to keep chaining
  return this;
}

$("#input1").highlight_input();
$("#input2").highlight_input();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input>


Even you can pass the color as an argument in case you want to apply custom color in some case.

jQuery.fn.highlight_input = function(color) {
  // if argument is undefined use the default value
  // although you can return in the same line since 
  // css method returns the object reference
  return this.css("background", color || "yellow");
}

$("#input1").highlight_input();
// passing color as argument
$("#input2").highlight_input("red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input>

Sign up to request clarification or add additional context in comments.

4 Comments

You are on the right path but not the right way. read this and adapt your answer. api.jquery.com/jquery.fn.extend
Also, keep in mind that doing a jq selector may return you and array of objects.
@DincaAdrian : extend is using to add multiple properties.... which provides the same behaviour
@DincaAdrian : jQuery selector returns an array like object and not an array.... by index we can retrieve DOM object... to get jQuery object we can use eq() method.....
0

jQuery plugins will do the job

$.fn.highlight_input = function(){
  return this.css({background:"yellow"});
}

you can additionally pass a desired color argument (that will fallback to yellow

$.fn.highlight_input = function(color) {
  return this.css({background: color||"yellow"});
}

use like

$("selector").highlight_input("#f80");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.