Home > Tags > JavaScript
Page 7

A Simple Way to Add Free News Content to Your Website

A challenge that many website owners face is how to supply continuously fresh content for new and repeat visitors to peruse.

It can be a very time-consuming task to manually upload regular updates. Fortunately, there is an easy way to showcase free, readily available news content on a wide variety of topics.

We will examine a quick and effective method of incorporating RSS (Really Simple Syndication) coding in order to add news content to any site. First, let’s look at what RSS is, and how it works.

RSS is an online coding solution that delivers automatic updates for Web content. Say, for instance, you add an RSS code for international news to your website from a popular source, such as CNN, Reuters, or the BBC. Visitors would be able to access new content links as often as the source updated their news feed. In other words, you get the benefit of presenting the very latest desired information online, with no effort on your part.

Due perhaps to a misguided perception that it is difficult to add the necessary coding to make RSS work within a website’s framework, it remains an extremely underutilized resource.

A typical RSS newsfeed (this one from the BBC) looks like:

http://feeds.bbci.co.uk/news/world/rss.xml

When the XML document is updated by the BBC, the new information is automatically displayed on any website that has incorporated the above URL to obtain World News.

You can find RSS feeds all over the Web; just look for the small orange icon with a dot and two waves above it. The very latest data is available on diverse subjects ranging from international news, to financial updates, to reports on innovations in the food and drink industry, to the latest updates on plants and gardening.

So, now that we have a better understanding about RSS and what it can do, let’s move on to finding out how to incorporate the correct coding into a website in order to gain the noted benefits.

Google Feed API

Google has developed an exceedingly convenient method to display RSS feed data, via their Feed API feature. Using this technique, you can showcase any newsfeed by incorporating some simple Javascript lines into a web page.

To begin utilizing the Feed API, insert the following script into the Head section of your web page, beneath the meta tag area and just in front of the closing Head tag:

<script type="text/javascript" src="https://www.google.com/jsapi"></script> <script src="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js" type="text/javascript"></script> <style type="text/css"> @import url("http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css"); #feedControl { margin-top : 10px; margin-left: auto; margin-right: auto; width : 440px; font-size: 12px; color: #9CADD0; } </style> <script type="text/javascript"> function load() { var feed ="http://feeds.bbci.co.uk/news/world/rss.xml"; new GFdynamicFeedControl(feed, "feedControl"); } google.load("feeds", "1"); google.setOnLoadCallback(load); </script>

Then, insert the following code into the desired area of the web page:

<div id="body"> <div id="feedControl">Loading...</div>...
more →
Jeff_DD says: True, you are not going to get an SEO boost from this however any site that is useful to its community is certainly going to get...

Implementing Drag and Drop Functions with HTML5 and JavaScript

With HTML5 and JavaScript, you can implement native drag and drop functions within the Web browser.

This is one of the emerging HTML5 tools that promises to make websites more interactive without relying on additional technologies such as Flash. In this tutorial we will create a simple page with images the user can drag and drop into designated areas.

Create an HTML5 Web Page

Create an HTML file for your drag and drop function. Use the following basic outline, with sections for JavaScript and CSS in the head area:

<!DOCTYPE HTML> <html> <head> <style type="text/css"> /*styling here*/ </style> <script type="text/javascript"> //functions here </script> </head> <body> <!--page elements--> </body> </html>

Add Drag Targets to the Page

Your page will contain elements that can be dragged and elements in which the dragged items can be dropped. Start with the areas your user will be able to drop draggable elements into, adding the following in your page body section:

<div class="pics"> <div id="place1" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </div> <div id="place2" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </div> <div id="place3" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </div> <div id="place4" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </div> <div id="place5" ondrop="dropIt(event);" ondragover="event.preventDefault();">...
more →
Romain says: I think you should consider keeping the JS stuffs in js part and not in the div / img tags as you did in the second part, using...

Coding Vendor Prefixes with JavaScript

Savvy web developers often use vendor prefixes to try out the latest browser styles before the styles have been approved by the W3C and turned into a standard.  By specifying a browser or vendor prefix within your CSS stylesheet or style property within a JavaScript function, you can gain control of how an element will render within a specific browser (Chrome, Firefox, IE, etc.).

This gets you access to these browser’s newest and coolest styles and elements.  This article will illustrate how to use a JavaScript function to identify which vendor prefix is needed for the user’s browser. This technique has been adopted by the Microsoft MSDN team as a best practice for their demos.

Before diving into the tutorial, I want to stress the caveats with using vendor prefixes in both CSS and JavaScript.  While vendor prefixes can open your web pages to all the neat stuff companies have packed into their browsers. They can also render your code worthless if a vendor decides to drop support for the style you are accessing.  This happens when the vendor’s request for a new standard is not adopted by the W3C. The W3C is slow to adopt new standards and sometimes a vendor will withdraw its request in order to pursue other technologies. If you choose to employ vendor prefixes in your pages, you will want to make sure your code or stylesheets will still render beautifully when the vendor prefix is no longer found.

Here is an example of a JavaScript setting the transform style using vendor prefixes. (This could also be done in a CSS stylesheet, but this article is focusing on JavaScript.)

var oElement = document.getElementById("myElement"); oElement.style.msTransform = 'scale(2)'; //IE oElement.style.webkitTransform = 'scale(2)'; //Chrome and Safari oElement.style.MozTransform = 'scale(2)'; //Firefox oElement.style.OTransform = 'scale(2)'; //Opera oElement.style.transform = 'scale(2)'; //Someday this may get adopted and become a standard, so I put it in here.

As you can see, if you plan to use vendor prefixes for several styles in your site, this technique can get clunky and time consuming to code. Instead, a better way to find the supported browser is to loop through each vendor prefix to find the right property or return null if one is not found:

function GetVendorPrefix(arrayOfPrefixes) { var tmp = document.createElement("div"); var result = ""; for (var i = 0; i < arrayOfPrefixes.length; ++i) { if (typeof tmp.style[arrayOfPrefixes[i]] != 'undefined') result = arrayOfPrefixes[i]; } else { result = null; } return result; }

The next step is to initialize a variable for all the properties using vendor prefixes in your page.

var transformPrefix = GetVendorPrefix(["transform", "msTransform", "MozTransform", "WebkitTransform", "OTransform"]); var transitionPrefix...
more →
Dominique Sandoz says: Thanks, just a warning for other people visiting this: Code is buggy and contains logic errors, you may have to correct these...

Developing a Responsive Website Part 4: Finishing The Homepage Portfolio Slider

This week we’re going to finish up the portfolio slider on our homepage that we have already started.

At this point, if you view your index.php file and scroll down to the secondary screen it should look something like this.

We’re close, all we have to do now is plug in our jQuery elements and then add some CSS to make our secondary portfolio slider screen responsive.

Go ahead and download the Java files you’ll need from here, keep the js directory in your root folder and check out what out the image below to see what your finished product will look like.

Let’s begin in our index.php file.  The first thing we’re going to do is add some links inside our heading that point to our java scripts. These are the jQuery and JavaScript’s that power our slider. As you can see I sandwiched mine between the link to my style sheet and the closing of the head tag.

<link href="main.css" rel="stylesheet" type="text/css" /> <script src="js/jquery-1.2.1.pack.js" type="text/javascript"></script> <script src="js/jquery-easing.1.2.pack.js" type="text/javascript"></script> <script src="js/jquery-easing-compatibility.1.2.pack.js" type="text/javascript"></script> <script src="js/coda-slider.1.1.1.pack.js" type="text/javascript"></script> <script type="text/javascript"> jQuery(window).bind("load", function() { jQuery("div#slider1").codaSlider() // jQuery("div#slider2").codaSlider() // etc, etc. Beware of cross-linking difficulties if using multiple sliders on one page. }); </script> </head>

At this point you should have a fully functioning slider, but it’s not quite responsive yet.  To make our slider responsive we just have to add a few more things in our media queries and we’ll be done.  First up will be our media query for landscape view tablets with a max width of 1024 px, all we need to do is add our #mainBG2 tag under our #mainBG tag.

#mainBG2 { border-top:10px solid #EDEAE5; background:...
more →
Jeff_DD says: Here is the one that kicked off the series. I will post links to each one of these for the readers....

Pushing Updates to the Web Page with HTML5 Server-Sent Events

The HTML5 Server-Sent event model allows you to push realtime data updates from the server to the browser.

In this tutorial we will work through the process, with the EventSource object handling received data and writing it to the page. We will use HTML5 and JavaScript at client side, with PHP at server side.

With existing models such as AJAX, the code in a Web page would continually ask the server to supply new data, but the onus was on the client to request the information. With Server-Sent requests, you can stream data from your server, with updates pushed from there without the code at client side having to keep requesting it. Once your page initiates the Server-Sent event, the server script can continue sending updates. Your JavaScript code can write this new data into the page whenever it receives it.

Create an HTML5 Page

Create your HTML5 page as follows:

<!DOCTYPE html> <html> <head> </head> <body> </body> </html>

Add an Element to Display the Server-Sent Data

We will display the data received from the server in a dedicated page element, so add the following in the body section of your page:

<div id="serverData">Here is where the server sent data will appear</div>

You can put any content you like in your element, as long as it has an ID attribute so that you can identify it in your script. The placeholder text should only appear when the page first loads, but will disappear when the script runs.

Add a Script to the Page

Because we want the function to continue receiving and handling updates, we add the script section in the body of the page. Of course your own pages may execute functions on user interaction, but for the purposes of this demonstration add the following script at the end of your page, before the closing body tag:

<script type="text/javascript"> //functions here </script>

The script will execute when the browser renders the page, so the Server-Sent events will be initiated straight away. Next add the JavaScript code inside this script section:

//check for browser support if(typeof(EventSource)!=="undefined") { //create an object, passing it the name and location of the server side script var eSource = new EventSource("send_sse.php"); //detect message receipt eSource.onmessage = function(event) { //write the received data to the page document.getElementById("serverData").innerHTML = event.data; }; } else { document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events."; }

The script first checks that the browser supports the EventSource model. If it doesn’t, an error message is written to the server data page element instead. If the browser does support the function, the Server-Sent process begins. First, the script creates an object of the EventSource class, passing it the URL of the server side script that will be providing the streamed data updates. Then the script sets up an event listener function to execute when the EventSource object receives an update from the server. When this happens, the script simply gets a reference to the update page element and writes the new data to it.

Create a Server Side Script

We now need to create the server side PHP script to send updates to the page. Create a new file and save it “send_sse.php” or another name of your choice, as long as you amend the JavaScript EventSource code above to reflect the correct name and location. Enter the following outline in your PHP file:

<?php //streaming code ?>

Begin your PHP script by setting the headers as follows:

header('Content-Type:...
more →
MIke says: It's really horrible when you make a tutorial that is the #1 google result, and it isn't even correct. As stated in the...

Making Use of HTML5 Storage

HTML5 offers lots of significant advantages to developers, but browser support is still pretty low. There’s no reason not to start inserting HTML5 functions into sites now, as long as you take the necessary steps to check for browser support and provide alternative content for everyone else.

In this tutorial we’ll go over the basics of using HTML5 and JavaScript to exploit the enhanced storage facilities on offer. With HTML5 you can store more data – and store it more efficiently.

The two main data storage objects are localStorage and sessionStorage. The localStorage data persists between sessions, while data stored using the sessionStorage object expires with the current user session. HTML5 storage data is not passed along with each browser request, so you can store large amounts of data while retaining a good level of efficiency.

HTML5 Page Outline

Use the following outline for your HTML5 page:

<!DOCTYPE html> <html> <head> <script type="text/javascript"> /*Functions here*/ </script> </head> <body> </body> </html>

We will add our storage functions within the script section in the head area and also within the page body, where we will place a few simple elements for demonstration.

Local Storage

The JavaScript localStorage object allows HTML5 pages to store data items at client side, then access these items during future sessions. To demonstrate, add the following to the body section of your page:

<input id="userText" type="text"/> <input type="button" value="store" onclick="storeText('userText')"/> <div id="result"> Result here </div>

Here we have added a text-field, a button calling a function, which it passes the ID of the text-field input element, and a div element with some placeholder text content. When the user presses the button, any text they have entered in the text-field is going to be stored using the localStorage object. Add the following function to your script section in the page head:

function storeText(inputID) { //check to see if the localStorage item already exists var userInput = localStorage.userInfo; //set it up for new data to be appended if(userInput!=null) userInput+=" "; else userInput=""; //add the new data userInput += document.getElementById(inputID).value; //set the localStorage field with the updated data localStorage.userInfo = userInput; //write it to the page document.getElementById("result").innerHTML...
more →
Ecommerce reviews says: Nice post! As i know that the HTML5 has the more functionality to the use to design the webpage like drag and drop, playing video...

What Can You Do With Paper.js?

There are many JavaScript frameworks that leverage HTML5.

Paper.js is one of these frameworks that uses Document Object Model (DOM) to structure objects in an easy-to-understand manner.  It offers creative and neat ways of doing lots of stuff on a Web browser that supports the <canvas> tag. It also offers a new and interesting approach to drawing vector graphics.

The basic setup is shown below:

<script src="js/paper.js" type="text/javascript"></script> <script src="js/main.js" type="text/paperscript"></script> <canvas id="draw" width="100%" height="100%" resize="true"></canvas>

As you can see, the paper.js is included after which you add your code file under “type=”text/….” After passing the canvas element id that needs to be drawn and ensuring that your code file includes all the classes and functionality to be used with paper.js, then the rest is a matter of being creative while you leave the rest to paper.js.

Working with Predefined Shapes

Paper.js allows you to use predefined shapes of varying dimensions and create path items and segments. For example, the code below produces circle-shaped paths from the “Circle” constructor:

var myCircle = new Path.Circle(new Point(300, 70), 50); myCircle.fillColor = 'black';

This piece of code creates a black circle with a radius of 50pts and at the x position of 300 and a y position of y.

To create a rectangle, you pass the “Rectangle” constructor the same way as a circle as shown below:

var rectangle = new Rectangle(new Point(50, 50), new Point(150, 100)); var path = new Path.Rectangle(rectangle); path.fillColor = '#e9e9ff'; path.selected = true;

Creating Interaction

Paper.js also supports drag n drop functionality as well as keyboard strokes. An empty path is created on execution where segments can also be added as shown below:

// Create a new path once, when the script is executed: var myPath = new Path(); myPath.strokeColor = 'black'; // This function is called whenever the user // clicks the mouse in the view: function onMouseDown(event) { // If the path is empty, we need to add two segments // to the path. The first one will stay put, // and the second...
more →
David Gitonga says: Hi Rokcy. Here is the demo link. http://paperjs.org/examples/ The link contains different animations created using Paperjs.