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!
-
2Please explain what you're trying to do more clearly. What do you mean "when you need"?Soviut– Soviut2017年02月09日 07:17:44 +00:00Commented Feb 9, 2017 at 7:17
2 Answers 2
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>
4 Comments
eq() method.....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
Explore related questions
See similar questions with these tags.