Create a function OO in JavaScript

javascript
jquery

#1

Hello, I am working with PHP and JS, and I have to show message in the view in certain moments (with errors, with success, etc.). I acomplish this OK, first, I made it with a anonymous fuction(in the same page), second, I created a function to call (in the same page), third, I put this function in other .js file and i called it into my view, and all works OK. My problem is, I want to make this function generic, to use it in other times, passing a div id, but this doesn´t work. I put the two examples.

function general_alerts(){
        $("#alert").fadeTo(2000, 500).slideUp(500, function(){
            $("#alert").slideUp(500);
        });
    }

    $(document).ready (function(){
        general_alerts();
    });

this fuction works OK, but I need one in wich I pass a variable an replace the part of the id element $("#alert").

in the view

 $(document).ready (function(){
      var id = '#alert';
        general_alerts(id);
    });

in th .JS file

function general_alerts(id){
        $(id).fadeTo(2000, 500).slideUp(500, function(){
            $(id).slideUp(500);
        });
    }

the html element

<div class="alert alert-warning alert-dismissible fade show" role="alert" id="alert">
            <strong>Alert!</strong> <?php echo $error;?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
 </div>

This, doesn’t works, maybe I am ding something wrong. Hope that you can help me, thanks in advance.
Mary


#2

Sorry, I do not know how to delete this post, but maybe is helpfull to someone else. I resolve the problem, first, I put wrong the address to de .JS file, second, I pass the parameter directly to the method.

$(document).ready (function(){
        general_alert("#alert");
    });

in the JS file

function general_alert(id){
    alert("entre al alert en .JS");
    $(id).fadeTo(2000, 500).slideUp(500, function(){
        $(id).slideUp(500);
    });
}

#3

It’ll be that first bit that fixed it. Gotta include the right file :wink:


#4

We don’t tend to delete posts…

… and that’s why! :slightly_smiling_face:

Glad you fixed it!