Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell jQuery to run a function on one specific web page only?

I have some jQuery code that is on every web page of the site (in the head element).

What selector syntax can I use to tell jQuery that a certain function should only run on one page and not all the other pages on the site?

Can I specify a page name or URL in the selector somehow?

Many Thanks

like image 333
Joseph Avatar asked Jun 21 '10 18:06

Joseph


People also ask

How do I run a function only once in jQuery?

jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.

How do you attach a event to element which should be executed only once?

Syntax: $(". event-handler-btn"). one("click", function (e) { // Code to be executed once });

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


3 Answers

You could use an if statement checking for top.location.pathname.

if (top.location.pathname === '/my/path')
{
    /* magic ... */
}

Or if you want to make it more portable and give the actual if statement some meaning (so someone reading it will know what it's about) - if you have access to the body element of the document, you can add a class showing that you want to run this script.

So for instance, if /* magic ... */ in the above example has something to do with including the Facebook API, you could make your body look like <body class="has-facebook-api"> and then make a check with jQuery:

$(function () // on document.ready()
{
    if ($('body.has-facebook-api').length > 0)
    {
        /* magic ... */
    }
});

Make sure this runs after including jQuery inside a separate script tag.


While we're at it, if you're not using this script to transform the visuals of your page before it gets outputted, I'd advise you to place all or most of your script tags close to your footer to render the page sooner.

like image 102
Denis 'Alpheus' Cahuk Avatar answered Oct 31 '22 20:10

Denis 'Alpheus' Cahuk


Maybe check window.location.pathname?

if (window.location.pathname == "/path/to/page.html") {
    callFunction();
}
like image 39
Kyprus Avatar answered Oct 31 '22 20:10

Kyprus


You can't specify the current URL in a jQuery Selector, you can however write a simple check using the document.location object:

if (document.location.pathname == "/somefolder/somepage") {
   // do some special stuff on this page!
}
like image 27
gnarf Avatar answered Oct 31 '22 18:10

gnarf