Results for jQuery

Make Websites Efficient With Page Visibility

Saturday, September 19, 2020
Make Websites Efficient With Page Visibility
The video player will automatically play and pause depending on the visibility of the page.


Learn a few techniques to create a responsive website that efficiently handles being out of sight with the power-saving Page Visibility API.

We've had tabbed browsing for about a decade. Most users are familiar with the idea of having more than one website open at a time, but it's hard to deduce when your site has their attention. Traditional 'hacks' are to attach an onblur or onfocus listener, but these are far from flawless as they often give false positives.

Enter the Page Visibility API. Although this JS API is still in its infancy, it’s 'a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU-efficient web applications'. It's currently a W3C Candidate Recommendation which has been championed by Microsoft and Google, so it’s not surprising to find it's supported in Chrome 13 and will be supported in IE10, as well as Firefox 10 and Opera 12.10. In this tutorial we'll pause and play a video; prevent erroneous visits being added to page analytics; and stop Ajax requests until the user returns, saving greatly on server load.
Make Websites Efficient With Page Visibility
Although a tad dry, it’s well worth reading up on the W3C spec – it tells you most of what you need to know and can really help you out if you get stuck


STEP 1: Adding The Listener
It's incredibly easy to start using the Page Visibility API; if you’ve ever added a click handler this syntax will look very familiar. The visibilitychange event is triggered by several actions: when a user navigates to/from the tab your site is in, when the browser is minimized and when the OS is locked.

CODE:
document.addEventListener( 'visibilitychange', function() {
//do stuff
}, false);
/* jQuery way */
$(document).on( 'visibilitychange', function() {
//do stuff
});
Page not in view: evidence that our JavaScript is up and running by switching between tabs.
Page not in view: evidence that our JavaScript is up and running by switching between tabs.


STEP 2: Catering For All Browsers
Of course, this wouldn’t be web development if it were that easy. Currently, most of the browsers that support the Page Visibility API do so with their own vendor prefix (except Opera). To account for this we can quickly check if the prefixed version is undefined or not.

CODE:
var prefix;
if ( typeof document.hidden !== 'undefined' ) {
prefix = '';
} else if ( typeof document.webkitHidden !== 'undefined' ) {
prefix = 'webkit';
} else if ( typeof document.mozHidden !== 'undefined' ) {
prefix = 'moz';
} else if ( typeof document.msHidden !== 'undefined' ) {
prefix = 'ms';
} else {
window.alert('Your browser doesn\'t support the Page Visibility API');
return;
}

In view! Now to deliver all that rich content we’ve been saving up…
In view! Now to deliver all that rich content we’ve been saving up…


STEP 3: Helping Ourselves
Right, we've now determined if the browser supports the API and which vendor preix to use. To use this data though, we need to check the Boolean value of document.hidden. We could check for each prefix like if (document.hidden || document.webkitHidden ||, etc), but that could quickly get tiring for our fingers. Instead, we’ve written a function to prevent RSI.

CODE:
function isHidden() {
if ( prefix === '' || typeof document.hidden !== 'undefined' ) {
return document.hidden;
} else if ( prefix === 'webkit' || typeof document.webkitHidden !== 'undefined' ) {
return document.webkitHidden;
} else if ( prefix === 'moz' || typeof document.mozHidden !== 'undefined' ) {
return document.mozHidden;
} else if ( prefix === 'ms' || typeof document.msHidden !== 'undefined' ) {
return document.msHidden;
} else {
return null;
}
}

STEP 4: The Universal Approach
With that in place, we can simply call that function to determine the page’s visibility. You’ll probably notice that we have explicitly checked if hidden is false as opposed to the shorthand !isHidden() because that would evaluate as true if isHidden() returned null.

CODE:
document.addEventListener( prefix + 'visibilitychange', function(event) {
if ( isHidden() ) {
} else if ( isHidden() === false) {
}
}, false);

STEP 5: Video HTML
Now we’re starting to get to grips with the Page Visibility API it’s time to do something with it. To kick-off, we’re going to be pausing and playing a video when the user visits a different tab. We’ll start by writing the HTML for the video and include the visibility.js script.

CODE:
<video width="550" height="360" controls autoplay>
<source src="my-video.webm" type="video/webm; codecs='vp8.0, vorbis'">
<source src="my-video.mp4" type="video/mp4; codecs='avc1.4D401E, mp4a.40.2'">
<source src="my-video.ogv" type='video/ogg; codecs="theoravorbis"'>
<p>Your browser can't play this video :(</p>
</video>
<script src="visibility.js"></script>

STEP 6: Controlling The Video
HTML5 video allows us to control its playback with JavaScript through its own very simple API. We’re going to be using two of its methods: play() and pause(). To use these we need to lock on to the video’s node; this assumes it’s the only video element on the page by getting the first in the list.

CODE:
var video = document.getElementsByTagName('video')[0];
document.addEventListener( prefix + 'visibilitychange', function(event) {
if ( isHidden() ) {
video.pause();
} else if ( isHidden() === false ) {
video.play();
}
}, false);

STEP 7: Pause For A Moment
This has the desired effect! Marvel as you never miss a frame of video playback again. Unfortunately, our implementation will pause and start it even if the video has already been watched or was paused by the user. To get around this we are going to check if the video is paused at the point they navigate away from the page.

CODE:
if ( isHidden() ) {
paused = video.paused;
video.pause();
}

STEP 8: Play It Again…
In the previous step, we used a property called paused to check if the video was stopped; we’re now going to use some other properties specific to the video tag to make an educated guess as to whether the video should be played when the user navigates back to our site.

CODE:
if ( video.currentTime > 0 && !paused && !video.ended ) {
video.play();
}

STEP 9: Let’s Recap
Great! We should now have a video that only plays if it was playing, wasn’t paused, and hasn’t ended. This is a good example of progressive enhancement where – if the technology is available – we can add extra levels of functionality to make users’ lives a little easier.

STEP 10: Visibility State
As well as document.hidden the Page Visibility API also adds another attribute: document.visibilityState. This has four possible values: visible, hidden, unloaded, and prerender. Like hidden, it’s current vendor-prefixed so let’s first make a similar function to isHidden() that deals with this.

CODE:
function visibilityState() {
if ( prefix === '' || typeof document.hidden !==\'undefined' ) {
return document.visibilityState;
} else if ( prefix === 'webkit' || typeof document.webkitHidden !== 'undefined' ) {
return document.webkitVisibilityState;
} else if ( prefix === 'moz' || typeof document.mozHidden !== 'undefined' ) {
return document.mozVisibilityState;
} else if ( prefix === 'ms' || typeof document.msHidden !== 'undefined' ) {
return document.msVisibilityState;
} else {
return null;
}
}

STEP 11: Verifying Analytics
When looking at visibilityState the First two values make sense, but prerender is a bit weirder. Some browsers (such as Chrome) pre-render pages that they think the user will click on to speed up browsing. Because this counts as a page view it can skew analytics into thinking they’re getting more views than they really are. We can Fix this with the Page Visibility API.

CODE:
if ( visibilityState() !== 'prerender' ) {
//your analytics code
}

STEP 12: How Long?
You might also find it useful to work out how long a user has been away from your website – either for analytics or to modify an element of your page in some way. When the visibilitychange event is fired it gives us a number of properties – one of which is the timestamp for when the event occurred.

CODE:
if ( isHidden() ) {
timeAway = new Date(event.timeStamp);
}

STEP 13: We Missed You…
We've used JavaScript’s built-in Date object so that we can work with the UNIX timestamp. To calculate how long they were away we can simply subtract one date from the other. We’re also dividing it by 1,000 to convert milliseconds to seconds and rounding the result up to make it more readable.

CODE:
} else if ( isHidden() === false ) {
var delta = new Date(event.timeStamp) - timeAway;
window.alert('You were away for ' + Math.round(delta / 1000) + ' seconds');
}

STEP 14: Changing The Title
This only fires when they leave and come back, but what if you want to do something on your site once the user has been away for a certain amount of time? We can use setInterval() to check how long they’ve been gone. If the user is away for, say, ten minutes, we change the title to ‘Close me!’.

CODE:
setInterval(function() {
var delta = Date.now() - timeAway;
if ( delta > 600000 ) {
document.title = 'Close me!';
clearInterval( this );
}
}, 10000);
Amaze (or annoy) your users by telling them to close your tab by changing the page’s title after a set time.
Amaze (or annoy) your users by telling them to close your tab by changing the page’s title after a set time.


STEP 15: Reverting The Title
Once they come back, we want to change the title back to what it was; you can do this with a simple if statement. It’s worth noting that just because we can do things like this it doesn’t mean we necessarily should. Adding a setInterval when a page isn’t being viewed is extra load on the CPU, but on the other hand, it does offer developers some extra creativity.

CODE:
} else if ( isHidden() === false ) {
if (document.title !== 'Page Visibility API tutorial') {
document.title = 'Page Visibility API tutorial';
}
}
The tab preview shows it has still only made one request.
The tab preview shows it has still only made one request.


STEP 16: Turning To Ajax
Okay, so the last example was a bit gimmicky – it’s unlikely many web developers are going to start encouraging people to close their page after they’ve been gone for ten minutes! Perhaps a more useful application of the Page Visibility API is to stop Ajax requests when they’re not needed.

CODE:
var requests = [],
makeRequests;
function getSomething() {
}
function stopRequests() {
}
To visualise Ajax requests the counter increases for every request made.
To visualise Ajax requests the counter increases for every request made.


STEP 17: This Was A Triumph
The requests variable is going to store all requests (ideally you’d remove requests once they’ve been completed). We’re going to use the jQuery ajax method for its simplicity. Within the getSomething() function, add:

CODE:
var request = $.ajax({
url: ' HYPERLINK "http://lab.fetimo.com/pagevis/resource.json'" http://mysite.com/resource.json',
success: function(response) {
$('body').append(response.message + '<br>');
}
});
requests.push(request);
You probably have better things to do with requests than simply output "This was a Triumph", but whatever the message, the code is the same.
You probably have better things to do with requests than simply output "This was a Triumph", but whatever the message, the code is the same.


STEP 18: Cancel That
jQuery has a handy property called beforeSend on its ajax method which lets you – among other things – set custom headers and, ultimately, decide if the request should be made. We’ll use this to only send a request if the page is visible by returning false if the page is hidden; returning false stops the request from being made.

CODE:
request = $.ajax({
beforeSend: function() {
if ( isHidden() ) {
stopRequests();
return false;
}
},

STEP 19: Setting intervals
To simulate an Ajax-style application making many requests we'll set up a setInterval to make a request every second within getSomething(). We assign it to a variable so that we can clear it in the next step – otherwise, it would be making requests forever! We also don’t want multiple timers, so it has been wrapped in an if statement.

CODE:
if ( !makeRequests ) {
makeRequests = setInterval(function() {
getSomething();
}, 1000);
}

STEP 20: Abort!
Next, we'll write what stopRequests() is meant to do. We will loop through the array and use jQuery’s abort() function on each of the active connections. We’ll then clear the interval that emulates an application making requests for us and reset the variable to be undefined; if we didn’t do this it would remain as the ID of the setInterval.

CODE:
requests.forEach(function( request ) {
request.abort();
});
clearInterval( makeRequests );
makeRequests = undefined;

STEP 21: Initialise Requests
The last thing to do is initialize getSomething() to start making requests both when the page is visible and on initial page load. This will complete emulating a JavaScript app making requests so that we can see the effect of our dabbling with the Page Visibility API.

CODE:
} else if ( isHidden() === false ) {
getSomething();
}
}, false); //close event listener
getSomething();
Once we go back to the tab, it starts to make requests again.
Once we go back to the tab, it starts to make requests again.


STEP 22: Tidying up
Now that we know this works you can change the requests array from storing every request made to just active ones by removing them on request completion. If you know you only ever make one request at a time you can simply do request.pop(); however, here we’re going to compare each element in the array and see if it’s exactly the same as the variable in memory.

CODE:
complete: function() {
requests.forEach(function( req, i ) {
if ( req === request ) {
requests.splice( i, 1 );
}
});
}
Make Websites Efficient With Page Visibility Make Websites Efficient With Page Visibility Reviewed by Kamal Thakur on Saturday, September 19, 2020 Rating: 5

Fixed Headers and Web Fonts Explored

Saturday, September 19, 2020
Fixed Headers and Web Fonts Explored
Colour co-ordination: Getting the right colour palette is critical to creating a website that conveys the right message, works with its surroundings and is easy to view. Two tools to help you with this are Adobe Kuler (http://kuler.adobe.com) and Color Scheme Designer (http://colorschemedesigner.com).



Retro design, contemporary code: “The Kitchen Sink Studios site’s retro-inspired design uses HTML5, CSS3 and jQuery coding to allow for strong SEO and the ability to view it on all kinds of devices while preserving the design. Highly optimised CSS, streamlined navigation and heavy use of web fonts were just a few of the many approaches that went into the website.”

The right mix of web typography and HTML5 backgrounds can produce an imaginative and standards-friendly web presence, as seen in the Kitchen Sink Studios site. Typography is the key component and great use is made of a simple combo of typefaces, which are given extended mileage with clever use of colour, style size and positioning. The two font families forming a formidable partnership here are Bodoni and Brandon Grotesque. While they are the focal point, the background textures, images and colour palette all shout retro yet reined. On a more functional level, the single-page design uses a fixed header element, combined with a smooth scrolling script for the navigation.

#1 - Resource: Smooth Scrolling With Easing
Activating a link in the navigation menu sees the site deploy a smooth scrolling action down to the chosen section. This effect is all thanks to jQuery.

To use this the jQuery library needs to be referenced and either linked to or placed on the server. The obvious place to get this is http://jquery.com or you can use a web-based library as per Google – take a look here: http://code.google.com/apis/libraries/devguide.html#jquery for more info. To create the scrolling effect the Easing plug-in is used. A great example and guide can be found at http://bit.ly/bD57s4.

#2 - Technique: Fixed Navigation
STEP 1: Introducing The Nav Tag
Typically, the navigation menu of a site is kept inside its own specific div tag or, if it’s HTML5-friendly, it will reside inside the nav tag, as seen here. Whichever tag is being used, it needs to be placed in a fixed position in order to remain a constant element.

CODE:
<nav>
<ul>
<li>HOME</li>
<li>COMPANY</li>
<li>WORK</li>
</ul>
</nav>

STEP 2: Fix The div Tag Position
Fixing the position of a div tag is an incredibly straightforward task – in fact, the only thing that it requires is the application of the position tag. Add the following code – position: fixed; – to the nav, or relevant tag, as shown below (line 4) and save. The tag will now be locked into its position, which will enable the page content to scroll under the menu.

CODE:
nav{
height: 35px;
width: 1000px;
position: fixed;}

STEP 3: Add Some Padding…
Fixing the navigational tag will mean that the next div tag – say, for example, #maincontent (line 1) – will be effectively placed behind the nav tag; this means it will hide any content at the top of the tag. To accommodate this side-effect, you can apply a little padding (line 4) – approximately the same size as the nav height – to the top of the #maincontent tag.

CODE:
#maincontent {
height: 500px;
width: 980px;
padding-top: 50px;}

STEP 4: …or Float The Margins
An alternative solution to the padding option considered in step 3 is to add a margin (line 4) instead, but this on its own can cause the fixed header to adopt the margin and move the header down the page. To compensate for this, the tag can be floated to the left (line 5), which will move the header back to the top of the page where it belongs.

CODE:
#maincontent {
height: 500px;
width: 980px;
margin-top: 50px;
float: left;}

#3 - Inspiration: Borrow From The Past
There is no doubt that the design inspiration for the Kitchen Sink Studios website has gone back in time and borrowed a number of elements and ideas from the past. This gives it a fascinating old-fashioned feel, from the imagery to the graphical elements to the aged paper texture seen throughout.

But the element that probably most stands out in terms of its retro roots is the typography. The site makes extensive use of the Bodoni font which is cleverly partnered with Brandon Grotesque. To generate the sheer variety of type seen on the Kitchen Sink site a selection of weights, styles and colours have been used. The fonts are well complemented by the aged backgrounds and textures that surround them.
#3 - Inspiration: Borrow From The Past
#3 - Inspiration: Borrow From The Past


#4 - Technique: The @font-Face Generator
The web font revolution has seen an influx of new typefaces. Font Squirrel provides its own examples and code to get you started.

STEP 1: Find Favourite Fonts
There are a number of ways to use @font-face, but this is one of the best. First, obtain fonts from sources like MyFonts (www.myfonts.com) or FontSquirrel (www.fontsquirrel.com). Now head to www.fontsquirrel.com/fontface/generator.
STEP 1: Find Favourite Fonts
STEP 1: Find Favourite Fonts


STEP 2: Generate Code
Click Add Fonts and select the ones you want from your system. If using for web alone be aware of the different formats. Click the Agreement checkbox to activate the Download Your Kit button; this will provide a ZIP file with the necessary code and fonts.
STEP 2: Generate Code
STEP 2: Generate Code


STEP 3: On To The Web
Add the font to the same location as the HTML file being used; add all variations for greater compatibility. Now use the CSS file or add the @font-face code to a style sheet already being used. Finally, you need to add the appropriate code to a tag, ie: h1 {font: bold 50px ChunkFiveRoman;}.
STEP 3: On To The Web
STEP 3: On To The Web

Fixed Headers and Web Fonts Explored Fixed Headers and Web Fonts Explored Reviewed by Kamal Thakur on Saturday, September 19, 2020 Rating: 5

Scrolling Image Effects

Saturday, September 19, 2020
Scrolling Image Effects
Inform your users: This site has a preloader that pauses content from displaying until the images have loaded. This is great, but unfortunately, there is no feedback to tell the user what is happening, so it’s possible to think the site is broken as nothing appears for the first few seconds. A simple message to inform the user can make all the difference.


Emersing the user into the story: “This site is all about telling the YMCA’s story. One of their strengths is strong, emotional photography. We dug into their library to present fullscreen images that give the site immediate impact. The visuals were an opportunity to help set the mood and really draw the user in to each section of the story.” - Dan Bartley, Senior Designer

Inspiration: www.imagineourymca.ca

One of the greatest weapons in the arsenal of a web designer is the image, and we’ve come a long way since the days of placing the smallest possible picture on a screen. Now designers are using the image to lead the user experience and coupled with the rich typography that CSS3 offers, we are witnessing the boundaries of HTML5 web sites pushed to greater success. This is evident in the Imagine our YMCA site created by Domain7. This skillfully crafted site uses jQuery to fade between background images as the site scrolls and the content on-screen changes. This produces a well-designed site that really adds to the user experience of the site.

Emersing the user into the story: “This site is all about telling the YMCA’s story. One of their strengths is strong, emotional photography. We dug into their library to present fullscreen images that give the site immediate impact. The visuals were an opportunity to help set the mood and really draw the user into each section of the story.”

#1 - INSPIRATION: An Enhanced Annual Report
Imagine our YMCA is actually the annual report, and it cost the same as designing, printing, and distributing a traditional annual report but has a far greater reach and shareability. Using a narrative-based approach, the team at Domain7 adapted the traditional paper-and-coil annual report format for desktop and mobile web viewing. This allowed the design to focus on key messaging within the site, a one-page display, photo evidence including galleries and moving image, mobile design, and a paperless approach.

#2 - TECHNIQUE: Transitioning With Scroll
STEP 1: Create A New Page
In Dreamweaver create a new HTML5 webpage and add the code to the head section. This links us to jQuery and creates the body style and the style for fixing the image container on the page.

CODE:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<style type="text/css">
body{
margin: 0; height: 1800px;
min-height: 1800px; padding: 0;
}
imageSwap{
position: fixed; overflow:hidden;
top: 0px; left: 0px; width:100%;
}
#imageSwap.fixed {position: fixed;top:0 px;}

STEP 2: Style The Content
Here we position the images and fix the content in a div over the top of them in a semi-transparent box. This content is positioned on the page so that we have to scroll down to see the next section.

CODE:
.one {position:absolute; z-index:1;}.two {position:absolute; display:none;z-index:2;}
.content {
background-color:rgba(125,0,0,0.6);
padding: 10px; height: 850px; width:800px;
margin-right: auto; margin-left:auto;
position: relative; z-index:100;
}
#first{top:50px;}
#second{top:350px;}
</style>

STEP 3: Add The HTML
In the body section of the document add the following code. Here we add the div container imageSwap which holds the images we will use in the background. We then have two content areas that are positioned above this. Finally, we move into JavaScript and set up two variables to hold the page position.

CODE:
<div id="imageSwap"><img class="one" src="image01.jpg" /><img class="two" src="image02.jpg" />
</div>
<div id="first" class="content">Content Area 1</div>
<div id="second" class="content">Content Area 2</div>
<script language="javascript" type="text/javascript">
var thisPos=1;
var lastPos=1;

STEP 4: Using jQuery
The document ready function fixes the background div and detects scrolling. If the user scrolls past 900 pixels then they are at the second div container, so we fade in the second image while fading out the first image.

CODE:
$(document).ready(function () {
$('#imageSwap').addClass('fixed');
$(window).scroll(function() {
var yPos = $(window).scrollTop();
if (yPos > 900){
thisPos=2;
if(thisPos != lastPos){
$('.one').fadeOut(500);
$('.two').fadeIn(500);
}
}

STEP 5: Detecting First Content
Now the final code reverses the last bit. Save this document now and, assuming you have two images named image01.jpg and image02.jpg, you should have a page that changes the background depending on scrolling.

CODE:
if (yPos <= 900){
thisPos=1
if(thisPos != lastPos){
$('.two').fadeOut(500);
$('.one').fadeIn(500);
}
}
lastPos=thisPos;
});
});</script>
item"></a>

#3 - TECHNIQUE: Create The Content Background
The content background has an image with a rip down each side. This image is a semi-transparent PNG and is straightforward to create. We’re going to show the creation process using Photoshop to put the composition together.

STEP 1: Create The Gradient
Create a new document 800 pixels wide by 100 high in Photoshop with a transparent background. Choose light red and dark red as the foreground and background colours. Use the gradient tool to create a gradient across the screen.
STEP 1: Create The Gradient
STEP 1: Create The Gradient


STEP 2: Fade Image
Make the Opacity of the layer 50%, and then we need to search online for a rip or tear image. When you find one that’s black and white or transparent already, download it and open in Photoshop.
STEP 2: Fade Image
STEP 2: Fade Image

STEP 3: Add The Rip
Select the rip using a colour selection and drag it into the gradient document. Position it at the edge and with the rip selected, choose the gradient layer and hit delete. If you turn off the rip layer you will have a ripped edge. Repeat this for the opposite side.
STEP 3: Add The Rip
STEP 3: Add The Rip

Scrolling Image Effects Scrolling Image Effects Reviewed by Kamal Thakur on Saturday, September 19, 2020 Rating: 5

Interactive Maps With JavaScript

Saturday, September 19, 2020
Interactive Maps With JavaScript
Going beyond standard web design: To make your site really stand out requires you to go beyond standard design procedures and make your contently with interactive features. Adding features that allow your users to explore the content will create a unique and memorable experience; the key to this is making sure these features enhance the content.



Inspiration: www.taocommunity.com

Creating the experience: “Tao Community is a group of companies that boosts communal relations at its core. What better way of showing this than through an interactive map that reflects what they do? We challenge ourselves to create an experience and, at the same time, make it easy enough for the audience to know what Tao is all about. We wanted the map in greyscale so that we can focus more on the detail without overwhelming the user.”

With the steady rise of sites looking for rich media experiences without the use of Flash – especially in the light of the recent announcements from Adobe – JavaScript has become an increasingly important power source for these experiences. The Tao Community provides a huge map to explore that can be dragged with several clickable elements; these then load relevant content to the centre of the screen. Once this would have doubtlessly been the reserve of Flash, but with HTML supporting ever richer experiences, plug-ins can now be left behind. JavaScript is used here to grab the width and height of the window and make the image full screen, and then power the dragging functionality.

#1 - INSPIRATION: Illustration style
Some of the best sites have extremely stylised content and it’s usually this element alone that makes a site stand out from its rivals. When implementing a unique navigation system that involves exploring a map, the perfect solution is to have a stylised image. In this particular case the map is created like an illustration with a monochromatic colour scheme. This allows for the links to stand out against the background. It’s also worth noting that the links have all been placed towards the centre so the user doesn’t have to develop a repetitive strain injury in order to find the actual content!

#2 - TECHNIQUE: Draggable areas with JavaScript
STEP 1: Get The Library
There are a number of JavaScript libraries that offer the ability to create draggable content within a div area. The simplest that we found can be downloaded from www.switchonthecode.com/tutorials/javascripttutorial-draggable-view-in-a-container, but feel free to shop around for one that works best for you. Once downloaded link to it in the head section of the JavaScript with the code shown below.

CODE:
<script type="text/javascript" src="SOTC-Draggable_View_Example.js">
</script>

STEP 2: Let's Create The Draggable Content
Here we create a div that will have a 1-pixel solid black line around the edge of the div area. In this case, the div is set to be 1,000 pixels wide by 600 pixels high – however, you can change the size of this div tag to whatever scale is necessary for your content. Notice how the overflow is hidden because the image needs to be masked by the div area.

CODE:
<div id="containerBox" style="position:relative; border:1px solid black;width:1000px;
height:600px; overflow:hidden;" >

Click and Drag
Click and Drag: Clicking on the image allows it to be panned around by dragging with the mouse. This enables you to create interactive draggable content for your users similar to that found on the impressive Tao Community website.


STEP 3: Add An Image
Now we add this image inside the ‘containerBox’ div tag. Note that we have to use an image which is larger than the div area, otherwise it won’t be able to be dragged around when it’s clicked on. As you can see in the code, we’ve used an image here which is more than double the width and height of the div tag; this suits our purposes down to the ground.

CODE:
<img id="draggableElement" src="images/largepicture.jpg"
style="width:2530px; height:1688px; position:absolute;
top:-333px;left:-500px; cursor:move;" />
</div>

STEP 4: Add The JavaScript
The following JavaScript code can be added to the body area of the document. Here we store the element to be dragged in the variable ‘el’. At this stage, we also get the parent node, which is the surrounding div area. Finally from this area, we store the left-hand edge of the div tag.

CODE:
<script type="text/javascript">
var el = document.getElementById('draggableElement');
var parent = el.parentNode;
var leftEdge = parent.clientWidth - el.clientWidth;

STEP 5: Wrap Up The Code
The next variable that we add takes the top edge position of the draggable area. The final line of code below just sets this up to be the draggable object. All the real power is done in the library that we linked back in step 1. All you need to do now is save the document and preview in your web browser to check everything is working as it should. And there you have it; now your users can click and drag to their hearts’ content!

CODE:
var topEdge = parent.clientHeight - el.clientHeight;
var dragObj = new dragObject(el, null, new Position(leftEdge, topEdge), new Position(0, 0));
</script>

#3 - TECHNIQUE: Create Line-Art Images
Without a doubt, one of the coolest parts of the Tao Community website is the amazing artwork of the city. This is a time-intensive job that can be achieved by tracing a photo using Photoshop.

STEP 1: On The Right Path…
In the Paths, panel add a new path and switch to the Pen tool. Click on the outside of the buildings to trace the edges. If you need to deselect a path to start a new one, switch to the Direct Selection tool and click on the document, then switch back.
STEP 1: On The Right Path…
STEP 1: On The Right Path…


STEP 2: Stroke and Fill
Back in the Paths panel, click on "path 1" and hit the second icon from the left at the bottom which will stroke the path with the paintbrush. Choose a light grey colour and start adding shading to various parts of the image to create a sense of depth.
STEP 2: Stroke and Fill
STEP 2: Stroke and Fill


STEP 3: Add A New Layer
Create a new layer and use the Paint Bucket tool with a white foreground colour to fill the canvas with white. Next, add another layer and switch to the Brush tool. Choose a 2-pixel-sized brush and select black as the foreground colour.
STEP 3: Add A New Layer
STEP 3: Add A New Layer

Interactive Maps With JavaScript Interactive Maps With JavaScript Reviewed by Kamal Thakur on Saturday, September 19, 2020 Rating: 5
Powered by Blogger.