Behseini Behseini - 4 months ago 6
Javascript Question

Issue on Calling a Custom Method Targeting DOM

Can you please take a look at this demo and let me know why it is not working



function changeColor(item){
var item = $(this);
item.css("color", "green");
}

$(".changer").on("click", function(){
$('p').changeColor();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p >Name</p>
<button class="btn btn-default changer" type="submit">Changer</button>'




Answer

You need to define changeColor as jQuery plugin not as simple function .

 $.fn.changeColor=function(){

       this.css("color", "green");
 }

Then , no need anymore for item argument since you could access to target element in jQuery via this;

__

DEMO :

$.fn.changeColor=function(){
           this.css("color", "green");
}

    $(".changer").on("click", function(){
         $('p').changeColor();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p >Name</p>
    <button class="btn btn-default changer" type="submit">Changer</button>'

Comments