Categories
JavaScript Tips & Tutorials

How to include a JavaScript file inside a JavaScript file?

This is a pretty odd question to ask in the first place if you have been using JavaScript for a while. JavaScript files are called from HTML web pages who need them to manipulate the HTML elements so that the users have extraordinary interactive experience. You can’t include a JavaScript file inside another JavaScript file like you can with PHP files, but you can only include JS files from HTML files.

If you need something that’s in a JavaScript file such as a predefined function, just include the file before wherever you are using the function and it should be fine. For example, you are calling A.js from a HTML file:

<body>
<script type="text/javascript" src="A.js"></script>
</body>

There is a rather sophisticated function in B.js that A.js relies on. You are wondering how to include B.js in A.js so A.js works properly. No you can’t. The answer is not to include B.js in A.js but include B.js in the HTML file before it includes A.js.

<body>
<script type="text/javascript" src="B.js"></script>
<script type="text/javascript" src="A.js"></script>
</body>

Now all the code in A.js should work fine. This is because all HTML code are read, parsed and executed in basic sequence from top to bottom. It’s the same with JavaScript code. When you need something from another JavaScript file and want to use it on the web page, just include it in the HTML web page. You can’t include a JavaScript file in a JavaScript file.

Categories
JavaScript Tips & Tutorials

JavaScript: How to set focus to form elements?

Normally, when users click on any label tag with the cursor, the corresponding input field will be focused ready for input or selection. Therefore, you can always achieve the focus effect by this native function of HTML’s. Otherwise, you’d need a small dime of JavaScript to set focus to any form element on the fly upon a certain event:

// FormName is the name value of the form.
// FieldName is the name value of the field
// to be focused.
document.FormName.FieldName.focus();

Or by element ID:

// FieldId is the id value of the field
// element to be focused.
document.getElementById('FieldId').focus();

There you go, the tiny focus() function is what we all need.

Categories
JavaScript Tips & Tutorials

JavaScript: How to get the URL of the current web page?

To get the URL address of the current page with JavaScript, simply return the value of window.location.href:

document.write(window.location.href);

Which is the same with:

document.write(location.href);

There’s much more you can do with the JavaScript Location Object such as redirecting to another URL.

Categories
JavaScript Tips & Tutorials PHP Tips & Tutorials

PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?

This is a rather common problem for novice web developers. While it may seem at first glance that it’s easy for PHP and JavaScript to communicate with each other, but they actually cannot interact with each other directly. They are very different technologies built for distinct purposes.

How to transfer or pass variable values from PHP to JavaScript?

To pass variables or values from PHP to JavaScript, just write the PHP code to generate the client side JavaScript code as you would with HTML code:

<script>
var jsVar = "<?php echo $phpVar ?>";
</script>

To embed PHP code in *.js files you have to first make the server to parse JavaScript .js files for any PHP code so that they will be executed. After that, you can create classes or call to functions or do whatever that is allowed in PHP in the .js files just as you can with .php files.

How to transfer or pass variable values from JavaScript to PHP?

Simply put, you have no other way to let some PHP script know any variable value than to send a request to it. So, you will use JavaScript to send a request to the PHP script by a GET or POST request that bears the variable value.

You can trigger a redirection to the PHP script and pass the values via URL:

var age = 24;
document.location = 'http://www.example.com/script.php?age=' + age;

Or you can perform an XMLHttpRequest request by GET or by POST.

Categories
JavaScript Tips & Tutorials PHP Tips & Tutorials

How to execute / run PHP code inside JavaScript files?

Static files of JavaScript would survive most applications but sometimes the ability to include PHP code inside JavaScript scripts and generate the content of the script files on the fly by PHP is a better option. How does one do that?

The simplest solution is to just include PHP code inside the <script></script> section of your HTML templates / web pages because chances are, the file extension is .php:

<script>
var jsVar = "<?php echo $phpVar ?>";
</script>

Even if it’s not ending in .php, such as in .html or .htm, you can configure your server to parse all .html or .htm files for any PHP code, though with a little extra server burden.

Another solution for this is to make your server parse all files ending in .js. Just create a .htaccess if it doesn’t exist in the directory in which you wish to include and run PHP code inside all .js files. Add these lines at the end of .htaccess:

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Now you can add all the PHP code you can inside any JavaScript files with a .js extension, the server will automatically parse and run them when the client side requests the file.

Categories
JavaScript Tips & Tutorials

JavaScript: Confirmation / Warning before Leaving or Navigating Away from a Page

Things couldn’t be worse when you were half way editing something and accidentally navigated away from the editing page after a whole hour of typing work. Hitting the back button of your browser neither helped, all you had done was gone anyway.

This must be remedied in some way, if you are creating an application that needs the user to input stuff, especially lengthy articles. One approach is to automate draft saving every a few minutes, the other is to warn the user before he or she either intentionally or inadvertently navigate away from the editor page. You can achieve this by a straightforward snippet of JavaScript:

var warning = false;
window.onbeforeunload = function() { 
  if (warning) {
    return 'You have unsaved changes.';
  }
}

The warning variable can be timely altered according to the editing activities by the user. For instance, it is set true if the editing field is changed or does not equal to default value, or if the user triggers the onKeyUp / onChange event of any input fields:

var editor_form = document.getElementById("form_id");
for (var i = 0; i < editor_form.length; i++) {
	editor_form[i].onchange = function() {
		warning = true;
	}
}

This snippet must be put at the end of the page. Also, to avoid the warning when you press the form submit button, add this snippet after that:

document.getElementById("submit_button_id").onclick = function() {
    warning = false;
}
Categories
JavaScript Tips & Tutorials jQuery Tips & FAQ

How to define multiple CSS rules / properties in jQuery?

The simplest way to define a CSS rule in jQuery might be:

$(".sth").css("color", "#f00");

To define more than one CSS rule in a single jQuery line:

$(".sth").css("color", "#f00").css("font-style", "italic").css("text-decoration", "underline");

Which simply doesn’t look that good, especially if you intend to add more. A better way to specify multiple CSS rules or properties with jQuery is by a JSON object:

$(".sth").css( {'color' : '#f00', 'font-style' : 'italic', 'text-decoration' : 'underline'} );

However, it is recommended that you use .addClass() instead of .css() to separate the JavaScript logics and CSS styles for maintainability.

Categories
CSS & HTML Tips JavaScript Tips & Tutorials PHP Tips & Tutorials

How to redirect the visitor to another page or website?

This is one of the most common tasks in website development and also one of the most frequently asked question according to some of the keyword research tools. Well, you have 3 ways to achieve a web page redirection.

  1. Use PHP header() function to modify and send a HTTP Location header:

    header("Location: /thankyou.html"); // redirect the visitor to the /thankyou.html page on the same website

    header("Location: http://www.microsoft.com"); // redirect the visitor to Microsoft

    You will need to make sure there’s no output at all before the calling of the header function to avoid any headers already sent errors.

  2. Use the meta tag of HTML:

    <meta http-equiv="refresh" content="3;url=http://www.example.com/hi.html">

    Which will simply refresh the visitor’s browser window and redirect to http://www.example.com/hi.html in 3 seconds.

  3. Use JavaScript to manipulate the browser window location object:

    <body onload="document.location='http://www.example.com/'">

Categories
JavaScript Tips & Tutorials PHP Tips & Tutorials

PHP, JavaScript: Stop and prevent others from framing your site or web page

Though it does increase traffic and the pageviews, it doesn’t feel quite good with someone who’s loading your website or page as a part of theirs in the form of a <frame> or <iframe>, leeching your content as part of theirs. To prevent them from loading your pages this way, and make the visitor browser to load the entire window with your site on the "_top" level, you need some javascript:

<script type="text/javascript">
<!--
	if (self.location.href != top.location.href) {
		top.location.href = self.location.href;
	}
// -->
</script>

Basically, this snippet checks if the URL location of this frame is the same with that of the top frame that is the browser window, if negative, meaning your site or page is being framed from another site, the entire window is then loading your site as the only page.

On the other hand, you can also do this by the help of PHP or a combination of both. Just check the global variable $_SERVER[‘HTTP_REFERER’] against the URL of a particular leeching site, if it’s a match, stop serving the content and redirect the visitors to a warning page so that they know they can come to your website directly instead of from a frame or iframe:

if (strpos($_SERVER['HTTP_REFERER'], 'leechsite.com') !== false) { // if a match
	header("Location: /warning.html"); // redirect to /warning.html
	exit();
}

Pretty much the simplest solution to this.

Interesting: Make sure you give a read to this Q&A thread at Stack Overflow.

Categories
JavaScript Tips & Tutorials

How to change the browser window status bar text of Firefox with JavaScript?

It’s strange that you can accomplish this in IE while you can’t make it happen in Firefox. Well, that’s because the development team has decided that it’s potentially annoying and harmful for web developers to change the text of Firefox status bar whatever way they want.

So the simple answer is, you can’t. But there’s always some sort of switch that would turn on or off the custom modification of the status bar text.

Simply type about:config in the Firefox address bar and it would take you to a vault of hidden advanced settings not meant for common users. Filter: disable_window_status_change and you will see that Firefox has come disabled of window status change by default.

firefox window status change

You can switch it off by changing the Value to false. However that ain’t gonna help you much because the vast majority of other Firefox users have left it in default, thus the JavaScript trick won’t work on their browsers.