Javascript comparison and logical operators

These are a good reference, and are slightly different than other languages.

The conditional operator is one that I need to use a lot more.. it can reduce the lines of if then statements… variablename=(condition)?value1:value2
For example, lets do age verification for a bar in the U.S…
drinkable=(age<21)?”Too young”:”Old enough”;

Comparison operators:

Let’s say that x = 5 , then…

Operator Description Comparing Returns
== is equal to x==8 false
x==5 true
=== is exactly equal to (value and type) x===”5″ false
x===5 true
!= is not equal x!=8 true
!== is not equal (neither value nor type) x!==”5″ true
x!==5 false
> is greater than x>8 false
< is less than x<8 true
>= is greater than or equal to x>=8 false
<= is less than or equal to x<=8 true

Logical Operators

Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Timing events with javascript

The window.setTimeout() can trigger functions and events after a certain amount of time. Using them takes a certain technique that can take a while to master. I always liked to use flash for timing events and animations in my webpage, but we are in a new era with html 5 and browser scripting, so here we go.

The correct technique is to create a timeout object in a variable as so…

var booter = window.setTimeout(function(){alert('boot em out!');},10000);

you could then cancel the timed event with…

window.clearTimeout(booter);

However there is a problem with trying to call the clearTimeout() that was set in a function.

function LogTime() { var booter = setTimeout(function(){  alert('close pop and logout.change the time to 4  minutes'); }, 4000);  }// end log time function

 

When I try to cancel this from another script outside the function, The error that “timer is undefined” is really frustrating.

The key to solving this is to declare the booter variable outside the function, and then use the variable in the function.

var booter; function LogTime() { booter = setTimeout(function(){  alert('close pop and logout.change the time to 4  minutes'); }, 4000);  }// end log time function 

Now this code works well, and the timed event can be  cancelled when I want it to.

So need timer to loop every second.
var mytimer; function timeHer(){mytimer = setInterval(function(){//do something here every second}, 1000);}

Custom CSS Media Queries

I am developing my own responsive framework, and here is the notes and research.

Device resolutions:

Samsung Galaxy S 4inch:
Samsung Galaxy Tab 7inch:
IPad 9inch: QXGA  2048 X 1536  4:3 aspect ratio

Surface pro: hd720 1280 X 720 16:9 aspect ratio

PC’s at work:
WSXGA+ 1680 X 1050  16:10 aspect ratio
SXGA 1280 X 1024   5:4 aspect ratio

 

Available media query syntax

There are some exciting ways to access these. There are the standard height and width, combined with max or min,

@media all and (min-width:1280px)

but there is an exciting aspect ratio query to allow me to use the extra space at the bottom of the 16:10 sxga and wsxga+ resolution displays

@media screen and (device-aspect-ratio: 5/4), screen and (device-aspect-ratio: 16/10) { ... } 

Well this blows, I have spent two hours on this shit and I cant get the fucking max-height or min-height to work at all, and that is the whole reason that I need this query, to fill in the fucking space left on the bigger screens.the aspect ratio thing is ok, but its not firing correctly, and still applies the styles to the wrong places. Maybe with some adjustment, like put it at the top of the pile of queries.

 

Here are the docs.  https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

Detect Screen Resolution

Screen shot of resolution detector

Here is a handy tool I made for detecting the screen resolution of any device.

While testing and developing I  used this tool on Ipad, IPhone, Blackberry Playbook, Samsung Galaxy, Kindle Fire Asus Transformer and it all worked perfectly to allow me to create the perfect content for each type of device.

http://losguerosproductions.com/screendetector.html

 

 

build an object, and insert into dom using javascript and jquery

var div = document.getElementById("yourDivElement");
var input = document.createElement("textarea");// this isgreat if you don't need to put contents into the text area dynamically.an empty text area.
var button = document.createElement("button");
input.name = "post";
input.maxLength = "5000";
input.cols = "80";
input.rows = "40";
div.appendChild(input); //appendChild
div.appendChild(button);

$('<tr>').append(
$('<td>').append(
$('<a>', {
href: o.link,
text: o.word,
onclick: function() {someFunc(o.string);}
})     )

 

I have a list that I need to insert an new anchor with javascript(because you should always use native javascript when possible), and build its attributes using jquery.

To create the new anchor :

var myNewTag = document.createElement('a');

var mynewthingy=document.createElement(‘a’);
mynewthingy.setAttribute(“href”, “http://dwdenney.com”);
mynewcategory.innerText=”visit deedubs”;
$(“#mydomobject”).append(“<li id=’atempnameremovewhendone’></li>”);
var atempnameremovewhendone = document.getElementById(“atempnameremovewhendone”);
atempnameremovewhendone.appendChild(mynewthingy);

HTML5 vs Flash Animation

Here is my html5fun file

Here is one that I was messin with background colors to dominate the dom.

Here is the css gradients playground

 

 

The code is pretty straightforward. This solution to Flash is pretty lame to me. The Flash worked well in every device except the ipad, but now we have to code multiple file types for each audio or video we would wish to embed.

 

For example: where I would have made one flash movie to use everywhere, and maybe just skipped the I-audience, now I have to encode three html5 compatible files, as well as the flash player fallback. And honestly, the html5 versions just don’t function the same across platforms. We get a slightly different reaction in every browser, when the Flash one would be exactly the same everywhere it was displayed.

 

<video autoplay="autoplay" controls="controls" preload="auto">
<!-- HTML5 source list: -->
<source src="video/movie.mp4" type="video/mp4">
<source src="video/movie.ogv" type="video/ogg">
<source src="video/movie.webm" type="video/webm">
<!-- Fallback to Flash: -->
<object width="720" height="400" type="application/x-shockwave-flash" data="flash-fallback/FlashVideoPlayer.swf">
<param name="movie" value="flash-fallback/FlashVideoPlayer.swf" /> <param name="flashvars" value="file=video/movie.mp4" />
<!-- Fallback image: -->
<img src="videofail.jpg" width="720" height="400" alt="Can't load video." title="No video playback capabilities" />
</object>
</video>

 

Here are screenshots from a demo I created. Its a small animation , with an audio sound effect that should play on page load. In firefox, the audio is non existent, and even the fallback error isn’t working.

In Internet explorer, the audio plays, but there is an ugly control bar, and the animation won’t play when you click it.

Research on Ipad and android devices coming soon.

Flash is the perfect way to create accents and highlight art and animations on your webpages. Lets start by making a logo for the top of my site here. I would like to have some cool looking text, with animated effects, just to add some spark to my page. Thats what I will go for , a “sparking text” type of effect. It needs to be 627X65. The width is the most important part, as the height will be relative. For this purpose, we are going to use text, with an outline, a gradient fill and a drop shadow.

Now we can try recreate a similar text effect using pure html5. Here is a test of Apple’s “Hype”, an HTML 5 authoring program for graphics and animation. Their answer to the “hype” that they feel flash is riding on. HTML is a text markup language. And it does a great job of marking up the text. you can have fonts, and italics. Trying to make this text markup language perform animations and add graphical effects such as drop shadow and opacity is not what it was made for.

Fire up flash. bust out some cool text. add some sparking effects on touch. export it out and put in a page. now lets test the page on several devices including pc, mac and mobile.




Formatting currency fields using javascript

This actually uses jquery, but yo could replace the jquery with doc.getelem….

Here is a sick way to get rid of $ signs, commas and anything after decimal point.

for example: $45,000.45 becomes a clean number 45000 ready for calculations.

No, it doesnt round. just removes the change.

// strip out any $$ .00 and anything else
function stripper(who){
dirtynumber = $( who ).val();
cleannumber = parseInt(dirtynumber.replace(/[^d.]/g, “”));
$( who ).val(cleannumber);
}

Handling Events With J Query

jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passes to the function. http://docs.jquery.com/Events_(Guide)

$(document).ready(function() {     $("a").click(function(event) {         alert(event.target.id);     }); });
If the  <a> that is clicked were a game element, such as an ace card, the card could tell you "I am an ace of spades" for your code to do what ever.
$( "p" )
.html( newText )
.find( "span" )
.hover(function() {
$( this ).addClass( "hilite" );
}, function() {
$( this ).removeClass( "hilite" );
})
.end()
.find( ":contains('t')" )
.css({
"font-style": "italic",
"font-weight": "bolder"
});

Setting an event handler is not too difficult, but what about removing the event. I don’t want the user to be able to hit the button more than once and still fire the function. the only way that was working was to disable the button or hide it.  I finally found the technique that really works for me. The prop() is a powerful function with untold uses. Dealing with checkboxes seems to be something that would merit its own post. http://api.jquery.com/prop/

Here is a great way to remove a click event that you put inline:

<A href=”#” onclick=”mycoolfunk()” id=”thisbut”>my button or link</a>

$(‘#thisbut’).prop(“onclick”, null);

 

Update: I have been fighting with finding the best way to remove a click event from the button so the user cant hammer on it repeatedly. None of my solutions were working effectively in all situations: like actions on  a submit button are harder to remove than ones on a link.I couldn’t get the submit to submit to my will. I wanted to hide it onclick, not happenin. remove click event, not workin either. What the hell should I do?

Well, enter the .one()  — thats right. http://api.jquery.com/one/ The jquery docs have a function to only put one click event onto an object. This is perfect for a submit where we don’t want the user to be able to repeatedly press the figgin button cause they think everything should be so instantaneous. LOL.

 

But what about handling multiple events.  I have been looking for this for years… We have the  $( document ).on( "click", "#demo-page", function( e ) {alert(e.type)}); alerts(‘click’)

Well here’s how to handle multiple events with one on call:

 $( document ).on( "click press swipeleft swiperight", "#demo-page", function( e ){
alert(e.type); 
if ( e.type === "swipeleft"  ) {// do something only on swipeleft}
});// end doc.on funk

 

I will write up a demo page with this script so I can test it out and do stuff with events.

 

Using delegated events to allow dynamic elements to have the event handler.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Lets take for example the diploma application I am working on. I have some buttons that have styles and actions that need to be called, but the buttons are not in the dom until and unless the user accesses that particular step of the application. How do I assign the events and styles to non-existing buttons. I had tried a few various solutions before I read about this. Now lets go for this approach. I will delegate the event to the form element. That way, any dynamically added elements will still get the mouseover and mouseout effects.

$(“#diplomappform”).on(“mouseover mouseout”, “[name=’stepUpButton’]”, function(e){
if(e.type==”mouseover”){
$(this).removeClass(“blackouterstrokesmall”).addClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”);
}
if(e.type==”mouseout”){
$(this).removeClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”).addClass(“blackouterstrokesmall”);
}
});

 

Sometimes if  you have a mouse over event, the mouse out event will trigger accidently too early. Peter has worked out a fix for this: make a function to call the mouse over function instead of putting an anonymous function directly into the event.
var qlinkTrigger = function() {
$(“#qlink-box”).slideDown(“slow”, function() {
$(this).clearQueue();
});
}

$(“a#qlink-trigger”).hover(qlinkTrigger).click(qlinkTrigger);

$(“#qlink-box”).mouseleave(function() {
$(this).slideUp(“slow”);
});

$(“a.close-qlinkbox”).click(function() {
$(“#qlink-box”).slideUp(“slow”);
return false;
});