Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to execute js only on specific page
    primarykey
    data
    text
    <p>I was wondering what would be the best way to execute a java-script code only on specific pages.</p> <p>Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; ... include $content; .. &lt;/body&gt; &lt;/html&gt; </code></pre> <p>content 'info' contains a button, we want something to happen on click, content 'alert' should give as a message, when you hover a text field.</p> <p><strong>What is the best way to trigger these action, without running into an error, because the object is not found?</strong></p> <p><strong>Option one: using <em>window.location.pathname</em></strong></p> <pre><code> $(document).ready(function() { if (window.location.pathname == '/info.php') { $("#button1").click(function(){' //do something }) }else if(window.location.pathname == '/alert.php'){ $("#mytextfield").hover(){ alert('message'); } } </code></pre> <p><strong>Option two: checking if elements exists</strong></p> <pre><code>$(document).ready(function() { if ($("#button1").length &gt; 0) { $("#button1").click(function(){' //do something }) }else if ($("#mytextfield").length &gt; 0){ $("#mytextfield").hover(){ alert('message'); } } </code></pre> <p><strong>Option three: include the script in the loaded template</strong></p> <pre><code>//stands for itself </code></pre> <p>Is their a better solution? Or do I have to get along with one of these solutions?</p> <p>Your experience, usage or any links related to this topic are appreciated.</p> <p><strong>//EDIT:</strong> </p> <p>I might have choosen a bad example, the actual code would be somethin like:</p> <pre><code> mCanvas = $("#jsonCanvas"); mMyPicture = new myPicture (mCanvas); </code></pre> <p>where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload