Ramona Soderlind
Ramona Soderlind

Reputation: 213

JavaScript and Jquery: How can you call a jquery function from within a javascript function

I have a button in a form that when clicked sends a variable to a javascript function. When the variable equals "link" I want to call a jquery function called makeLink().

This is what I have:

function getText(change)
{
   if(change == "link")
   {
      //call jquery function called makeLink()

   }

}

And here is my jquery function that creates a modal pop up with a form:

$(document).ready(function(){

function makeLink() {
    if ($("#makeALinkModalPopup").is(":hidden")){
    $("#makeALinkModalPopup").fadeIn("slow");

     $("#backgroundPopup").css({  
        "height": document.documentElement.offsetHeight

      });

    $("#backgroundPopup").css({"opacity": "0.7"});
    $("#backgroundPopup").fadeIn("slow"); 

        }

    }


});

Thanks for your help.

Upvotes: 0

Views: 237

Answers (4)

mplungjan
mplungjan

Reputation: 178422

Remove the document.ready wrapping to make makeLink available to the rest of the page

    function getText(change){
      if(change == "link") {
      //call jquery function 

        makeLink()

      }
    }


    function makeLink() {
      if ($("#makeALinkModalPopup").is(":hidden")){
        $("#makeALinkModalPopup").fadeIn("slow");

        $("#backgroundPopup").css({  
          "height": document.documentElement.offsetHeight

        });

        $("#backgroundPopup").css({"opacity": "0.7"});
        $("#backgroundPopup").fadeIn("slow"); 

      }
    }

Upvotes: 2

Frobzig
Frobzig

Reputation: 324

Move makeLink to the global scope and call it normally. There are only JavaScript functions. The distinction you are seeing is scope only.

Read about scope here.

As someone else said, remove the document.ready wrapping. Your function need not be defined there, because it cannot be seen outside of document.ready.

Upvotes: 1

Lemex
Lemex

Reputation: 3804

You dont need the dom ready.

Just have

function makeLink() {
    if ($("#makeALinkModalPopup").is(":hidden")){
    $("#makeALinkModalPopup").fadeIn("slow");

     $("#backgroundPopup").css({  
        "height": document.documentElement.offsetHeight

      });

    $("#backgroundPopup").css({"opacity": "0.7"});
    $("#backgroundPopup").fadeIn("slow"); 

        }

    }

Just have

function getText(change)
{
   if(change == "link")
   {
      makeLink();

   }

}

If you wanted to use the function on the dom ready then you would need to do.

$(document).ready(makeLink); < I might be wrong in sytax but to be safe i know this works..

$(document.ready(function(){
// do what ever you want
//even call make link

makeLink();
}

Upvotes: 0

Vasco Costa
Vasco Costa

Reputation: 341

You shouldn't define the function inside the document ready event, but on a separate file.

Then, where you have:

//call jquery function called makeLink()

Just put

makeLink()

Upvotes: 0

Related Questions