lundi 29 juin 2015

How to create an div background that is not affected by page zoom with CSS


My question is going to be pretty concise. I saw this Deezer page and I tried to zoom in and out to see that the image is "out of zoom" (see the image below)

enter image description here

Below is a structure we consider to be my page:

<body>
  <div class="visual-header">
    <div class="container">
       SOME TEXT
    </div>
  </div>
  PAGE CONTENT
</body>

How am I supposed to use image.png of a size of 2000x800 pixels to get this effect?


How to output multiple fields to a single page


I am looking to output text from multiple fields to a single page so that I can just copy and paste it. I made a basic HTML document with fields and I just want to hit submit and have it output all of the information condensed into one page all together. This is what I have

<style>
form {
  padding-top: 30px;
  min-width: 458px;
  > div,
  > fieldset {
    border: 0;
    padding: 0;
    margin: 0 0 8px 0;
    clear: both;
  }
  label,
  legend {
    float: left;
    width: 50px;
    padding: 7px 10px;
    &.radio-label {
      float: none;
      padding: 0;
    }
  }
  .choice-group {
    padding: 7px 10px 0 10px;
  }
  input[type=checkbox],
  input[type=radio] {
    margin-right: 20px;
  }
  input[type=text],
  input[type=email],
  input[type=password],
  input[type=number],
  textarea {
    width: 200px;
    border: 1px solid darken(tan, 20%);
    padding: 7px 10px;
    border-radius: 4px;
    outline: 0;
    &:focus {
      border-color: black;
    }
    &.short {
      width: 60px;
    }
    &.medium {
      width: 150px;
    }
    &.very-short {
      width: 40px;
    }
    &.long {
      width: 300px;
    }
  }
}

.screen-reader {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

body {
  background: #E27C37;
  padding: 20px;
  font-size: small;
}
</style>
<h1>Prefill Machine</h1>

<form action="#0" id="form">

  <div>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" placeholder="Digby Coyier" required>
  </div>

  <div>
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="digby@digby.com" required>
  </div>

  <div>
    <label for="name">Username</label>
    <input type="text" name="username" id="username" placeholder="digby2007" required>
  </div>

  <div>
    <label for="name">Password</label>
    <input type="password" name="pw" id="pw" required>
  </div>

  <div>
    <label for="name">Repeat</label>
    <input type="password" name="pw-repeat" id="pw-repeat" required>
  </div>


  <fieldset>
    <legend>Radio Choice</legend>

    <div class="choice-group">
      <label class="radio-label" for="radio-choice-1">Choice 1</label>
      <input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />

      <label class="radio-label" for="radio-choice-2">Choice 2</label>
      <input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
    </div>
  </fieldset>

  <div>
    <label for="select-choice">Select Choice</label>
    <div class="choice-group">
      <select name="select-choice" id="select-choice">
        <option value="Choice 1">Choice 1</option>
        <option value="Choice 2">Choice 2</option>
        <option value="Choice 3">Choice 3</option>
      </select>
    </div>
  </div>

  <div>
    <label for="message">Message</label>
    <textarea cols="40" rows="8" name="message" id="message"></textarea>
  </div>

  <div>
    <label for="cc">Credit Card #</label>
    <input type="text" name="cc" id="cc" placeholder="4242 4242 4242 4242" required>
  </div>

  <div>
    <label for="exp-1">Expiration <span class="screen-reader">Month</span></label>
    <input class="very-short" type="number" name="exp-1" id="exp-1" placeholder="08" min="1" max="12">
    <label for="exp-2" class="screen-reader">Expiration Year</label>
    <input type="number" name="exp-2" class="very-short" id="exp-2" placeholder="16" min="14">
  </div>

  <div>
    <label for="exp-1">CVV</label>
    <input class="short" type="text" name="cvv" id="cvv" placeholder="123">
  </div>

  <div>
    <label for="name">Address</label>
    <input type="text" class="long" name="address" id="address" placeholder="123 Super Street">
  </div>

  <div>
    <label for="city">&nbsp;<span class="screen-reader">City<span></label>
    <input type="text" name="city" id="city" class="medium"  placeholder="Milwaukee">
    <label for="state" class="screen-reader">State</label>
    <input type="text" name="state" class="very-short" id="state" placeholder="WI">
    <label for="zip" class="screen-reader">Zip</label>
    <input type="text" name="zip" class="short" id="zip" placeholder="55555" pattern="(\d{5}([\-]\d{4})?)" required>
  </div>

  <div>
    <label for="agree-terms">Agree?</label>
    <div class="choice-group">
      <input type="checkbox" name="agree-terms" id="agree-terms">
    </div>
  </div>

  <div>
    <input type="submit" value="Submit" id="submit-button">
  </div>
</form>

I want the page to fill in everything when I click submit so I will look like the following:

Name: John Smith
Email: John.Smith@mail.com
USERNAME: JSMith
Password:123456
Choice 1

And so on

This way I can just copy and paste it all into an email or a text file.


Fix thead on the top of all page


I am trying to table print using by CSS @media print.I search this type of case every where, I found similar type of solution but it can't work.

Currently I am using Google chrome version 43.0 and FireFox 38.0.5, FireFox is repeat the thead in every pages and arranging tr lines automatically, but chorme not working on the same case.

Is it possible to print using by CSS @media print? I hope you understand what I mean and your kindly suggestion.

Click here to view code


Filter content with smooth sliding animation


I am building a filter that is similar to isotope. The problem I am having is the smoothness when removing items. I translate the items (0,0) to get the effect of scaling out, while also removing their width (width: 0px) causing the items to shift over. I was wondering what I could do to make it not feel so rough?

I have tried using a .each() with a delay to ease the transition of all the items at the same time, but it gives it a very linear feel. I have also removed the items completely in a timeout that waits for the animation to complete.

Here is a working JSFiddle.

JS/JQuery

$(document).ready(function() {
    var navItem = $("nav ul li"),
        clear = $("nav li.clear"),
        first = $("nav li.first"),
        second = $("nav li.second"),
        third = $("nav li.third"),
        items = $(".items li"),
        notItem1 = $(".items li:not([data-exhibit='first'])"),
        notItem2 = $(".items li:not([data-exhibit='second'])"),
        notItem3 = $(".items li:not([data-exhibit='third'])");

    var active = "is-active",
        hidden = "is-hidden";

    navItem.on("click", function() {
        navItem.removeClass(active);
        $(this).addClass(active); 
    });

    clear.on("click", function() {
        items.removeClass(hidden);
    });

    first.on("click", function() {
        items.removeClass(hidden);
        notItem1.addClass(hidden);
    });

    second.on("click", function() {
        items.removeClass(hidden);
        notItem2.addClass(hidden);
    });

    third.on("click", function() {
        items.removeClass(hidden);
        notItem3.addClass(hidden);
    });

});

HTML

<nav>
    <ul>
        <li class="clear">view all</li>
        <li class="first">First</li>
        <li class="second">Second</li>
        <li class="third">Third</li>
    </ul>
</nav>

<ul class="items">
    <li class="third" data-exhibit="third"><img src="http://ift.tt/1Lyw7PG" alt=""></li>
    <li class="first" data-exhibit="first"><img src="http://ift.tt/1Lyw7PI" alt=""></li>
    <li class="second" data-exhibit="second"><img src="http://ift.tt/1kh2Ad7" alt=""></li>
    <li class="third" data-exhibit="third"><img src="http://ift.tt/1Lyw7PG" alt=""></li>
    <li class="first" data-exhibit="first"><img src="http://ift.tt/1Lyw7PI" alt=""></li>
    <li class="third" data-exhibit="third"><img src="http://ift.tt/1Lyw7PG" alt=""></li>
    <li class="first" data-exhibit="first"><img src="http://ift.tt/1Lyw7PI" alt=""></li>
    <li class="third" data-exhibit="third"><img src="http://ift.tt/1Lyw7PG" alt=""></li>
    <li class="second" data-exhibit="second"><img src="http://ift.tt/1kh2Ad7" alt=""></li>
    <li class="first" data-exhibit="first"><img src="http://ift.tt/1Lyw7PI" alt=""></li>
    <li class="second" data-exhibit="second"><img src="http://ift.tt/1kh2Ad7" alt=""></li>
    <li class="second" data-exhibit="second"><img src="http://ift.tt/1kh2Ad7" alt=""></li>
</ul>

SCSS

nav {
   width: 80%;
    margin: 25px auto;
    text-align: center;
    li {
        display: inline-block;
        padding: 5px 15px;
        background: #1abc9c;
        color: white;
        text-transform: uppercase;
        cursor: pointer;

        transition-property: background;
        transition-duration: .3s;
        &.clear { background: #7f8c8d; }
        &.first { background: #1abc9c; }
        &.second { background: #2ecc71; }
        &.third { background: #3498db; }
        &:hover, &.is-active { background: #333; }
    }
}

.items {
    width: 80%;
    margin: 0 auto;
    li {
        display: block;
        width: 25%;
        height: 150px;
        float: left;
        overflow: hidden;
        transition-property: transform, width;
        transition-duration: .5s;
        &.is-hidden {
            transform: scale(0,0);
            width: 0px;
            margin: -2px;
        }
        img { width: 100%; }
    }
}


Photoviewer Switching between divs


http://ift.tt/1Lyw5Hs

Hi all,

I have created a gallery of pictures which you cannot see with Jfiddle but all the code is there. I am attempting to have it so each time you click on an image one paragraph disappears and another emerges. The way I coded it works with one problem. If i click anywhere on the screen other than another image the paragraph disappears and another will not appear until I click an image. How can I code it so that the paragraphs will hide only if I click on one of the images and not if I click elsewhere as well. Thank you for your help!

Java:

        var request;
    var $current;
    var cache = {};
    var $frame = $('#photo-viewer');
    var $thumbs = $('.thumb');

    function crossfade($img) {

        if ($current) {
            $current.stop().fadeOut('slow');
        }

        $img.css({
            marginLeft: -$img.width() / 2,
            marginTop: -$img.height() / 2
        });

        $img.stop().fadeTo('slow', 1);

        $current = $img;
    };

    $(document).on('click', '.thumb', function(e){
        var $img;
        var src = this.href;
        request = src;

        e.preventDefault();

        $thumbs.removeClass('active');
        $(this).addClass('active');

        if(cache.hasOwnProperty(src)) {
            if (cache[src].isLoading === false) {
                crossfade(cache[src].$img);
        }
    } else {
        $img = $('<img/>');
        cache[src] = {
            $img: $img,
            isLoading: true
        };

        $img.on('load', function() {
            $img.hide();
            $frame.removeClass('is-loading').append($img);
            cache[src].isLoading = false;
            if(request === src) {
                crossfade($img);
            }
        });

        $frame.addClass('is-loading');

        $img.attr({
            'src': src,
            'alt': this.title || ' ' 
        });
    }
    });

    $(document).mouseup(function(e) {
        var container = $("#mad");
        jQuery("#para").hide();
        //toggle the componenet with class msg_body
        jQuery("#mad").click(function() {
            $(this).next($("#para").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para").hide();
        }

    })
    });
    $(document).mouseup(function(e) {
        var container = $("#ralph");
        jQuery("#para2").hide();
        //toggle the componenet with class msg_body
        jQuery("#ralph").click(function() {
            $(this).next($("#para2").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para2").hide();
        }

    })
    });
    $(document).mouseup(function(e) {
        var container = $("#julia");
        jQuery("#para3").hide();
        //toggle the componenet with class msg_body
        jQuery("#julia").click(function() {
            $(this).next($("#para3").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para3").hide();
        }

    })
    });
    $(document).mouseup(function(e) {
        var container = $("#sophie");
        jQuery("#para4").hide();
        //toggle the componenet with class msg_body
        jQuery("#sophie").click(function() {
            $(this).next($("#para4").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para4").hide();
        }

    })
    });
    $(document).mouseup(function(e) {
        var container = $("#may");
        jQuery("#para5").hide();
        //toggle the componenet with class msg_body
        jQuery("#may").click(function() {
            $(this).next($("#para5").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para5").hide();
        }

    })
    });
    $(document).mouseup(function(e) {
        var container = $("#kiss");
        jQuery("#para6").hide();
        //toggle the componenet with class msg_body
        jQuery("#kiss").click(function() {
            $(this).next($("#para6").fadeIn(500))
            if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $("#para6").hide();
        }

    })
    });
    $('.thumb').eq(0).click();

HTML



     <!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="Gallerystyle.css">
<ul class="navigation">
    <p> Nicholas Clegg </p>
  <li><a href="painthome.html">Home</a></li>
  <li><a href=favart.html>Artists</a></li>
  <li><a href="#">Sale</a></li>
  <li><a href="contact.html">Contact</a></li>
</ul>
</head>
<body>

        <div id="photo-viewer">  
<p id="para"> <em> "Maddy" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         niece. Her innocence and utter <br>
                         adorableness inspired Nick to <br>
                         draw this beautiful portrait <br>
                         of a young lady early in <br>
                         her life.</span></p>
<p id="para2"> <em> "Raplhie" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         grandfather. Nick captures the <br>
                         joy of ageing by encapsulating <br>
                         every detail of an older man  <br>
                         still in the prime of his life.</span></p> 
<p id="para3"> <em> "Julia" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         grandfather. Nick captures the <br>
                         joy of ageing by encapsulating <br>
                         every detail of an older man  <br>
                         still in the prime of his life.</span></p> 
<p id="para4"> <em> "Sophie" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         grandfather. Nick captures the <br>
                         joy of ageing by encapsulating <br>
                         every detail of an older man  <br>
                         still in the prime of his life.</span></p> 
<p id="para5"> <em> "Unknown" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         grandfather. Nick captures the <br>
                         joy of ageing by encapsulating <br>
                         every detail of an older man  <br>
                         still in the prime of his life.</span></p> 
<p id="para6"> <em> "Jo and Rich" </em> <br>
    <span class="normal">This is a picture of Nicholas'   <br>
                         grandfather. Nick captures the <br>
                         joy of ageing by encapsulating <br>
                         every detail of an older man  <br>
                         still in the prime of his life.</span></p> 
    </div>
        <div id="thumbnails">

        <a id ="mad" href="img/madeline.jpg" class ="thumb active" title="Madeline">
        <img id ="mad" src="img/madelinethumb.jpg" alt="Madeline" /></a>

        <a id="ralph" href="img/ralph.jpg"  title="Ralph" class="thumb">
        <img id="ralph" src="img/ralphthumb.jpg" alt="Ralph" /></a>

        <a id="julia" href="img/julia.jpg"  title="Julia" class="thumb">
        <img id="julia" src="img/juliathumb.jpg" alt="Julia" /></a>

        <a id="sophie" href="img/sophie.jpg"  title="Julia" class="thumb">
        <img id="sophie" src="img/sophiethumb.jpg" alt="Julia" /></a>

        <a id="may" href="img/may.jpg"  title="Julia" class="thumb">
        <img id="may" src="img/maythumb.jpg" alt="May" /></a>

        <a id="kiss" href="img/kiss.jpg"  title="Julia" class="thumb">
        <img id="kiss" src="img/kissthumb.jpg" alt="Joanna and Rich" /></a>
    </div>
<script  src='jquery-1.11.2.min.js'> </script>
<script src='photo-viewer2.js'> </script>

</body>
</html>


Optimize logic of jQuery Code


I have a very illogical jQuery code and I want to see if someone finds a better way to do the exact same thing:

jQuery:

$(".col-md-3 img").hover(function() {
    $(this).parent().children(".search").show();
    $(this).parent().children(".photo").css("opacity","0.4");
}, function(){
    $(this).parent().children(".search").hide();
    $(this).parent().children(".photo").css("opacity","1");
});

HTLM corresponding to this code:

<div class="col-md-3">
    <img class="photo" src="img/1_small.jpg" alt="img" />
    <img class="search hidden-xs" src="img/search.png" width="50px"/> 
</div>

I have multiple similar divs.


Accessing Javascript globals from aspx page to another


Here's the underlying folder structure:

|   ...
|   Top.aspx
|   ...
|
\---Include
        ...
        ClientScriptGlobals.aspx
        ...

Here's a snippet of Top.aspx:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Top.aspx.vb" Inherits="Project.Top"%>

<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"-->

<html>  
    <head><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10" />    
        <title>....</title> 
        <META HTTP-EQUIV="imagetoolbar" CONTENT="no">

        <!--#include virtual="..."-->
        <!--#include virtual="Include/ClientScriptGlobals.aspx" -->
        <!--#include virtual="...." -->
        ....
    </head>
</html>

And finally ClientScriptsGlobal.aspx:

<script language="javascript">      
    //Globals                   
    ...
    var FullTextSearchStatus = "<%= FullTextSearchStatus %>"
    ...
</script>


To give some context, Top.aspx includes ClientScriptGlobals.aspx so that I can access its global variables, which are also being used throughout the application.

My issue arises when I use aspnet_compiler.exe to pre-compile my application. Once it reaches ClientScriptsGlobal.aspx, it returns a bunch of errors like this:

error BC30451: Name 'FullTextSearchStatus" is not declared.

So now my question is, how can I tell ClientScriptsGlobal.aspx the location of FullTextSearchStatus's definition?

Keep in mind that when I opt to not pre-compile the application, these errors do not occur because the Javascript is not being compiled beforehand and therefore, its references have already been established (if that's the correct way describe this).


JCanvas restrict drag-and-drop layer for only right click


I'm using JCanvas for my isometric game. How to restrict the draggable layers to work only with the right mouse button?

So I would like to drag-and-drop my layer only with the right mouse button.

My render code is:

$c.drawImage({
    layer: true,
    groups: ['terrain'],
    dragGroups: ['terrain'],
    source: 'img/tileset.png',
    x: x_pos, y: y_pos,
    sWidth: 64,
    sHeight: 32,
    sx: map[x][y]*64, sy: 0
});


how create mailing list with meterjs and mailgun?


How to create a Mailing List with MailGun on meteorjs app? I know how to do ut with mailchimp; do a lot of search on google but nothing found ;(

Thank's


External function call from JSNI is not working


I am trying to translate this JavaScript code to JSNI code.

Script Imports

<script src="jquery-1.11.2.min.js"></script>
<script src="jquery.typeahead.min.js"></script>
<script src="autocompletetest/autocompletetest.nocache.js"></script>


Script

$('#q').typeahead({  
    minLength: 1,  
    order: "asc",  
    group: true,   
    groupMaxItem: 6,  
    hint: true,  
    dropdownFilter: "All",  
    href: "http://ift.tt/1HtBBLN}}",  
    template: "{{display}}, <small><em>{{group}}</em></small>",  
    source: {  
        country: {  
            data: data.countries  
        },  
        capital: {  
            data: data.capitals  
        }  
    },
    ...

To

$doc.getElementsByClassName("q").typeahead({
    ...
})

But I'm getting this error:

@com.citi.sevi.client.AutocompleteTest::loadJquery()([]): $doc.getElementsByClassName(...).typeahead is not a function

What could be causing this error?


Is binary hashing possible in javascript front end


I want to create an HOTP client using javascript similar to SpeakEasy

The above library is intended for server side javascript usage and it uses NodeJS.

I want to do the same thing on front end javascript in a browser but I haven't been able to use CryptoJS to achieve this behavior.

         var key = "abc";
         var counter = "123";

         // create an octet array from the counter
         var octet_array = new Array(8);

         var counter_temp = counter;

         for (var i = 0; i < 8; i++) {
             var i_from_right = 7 - i;

             // mask 255 over number to get last 8
             octet_array[i_from_right] = counter_temp & 255;

             // shift 8 and get ready to loop over the next batch of 8
             counter_temp = counter_temp >> 8;
         }

        // There is no such class called as Buffer on Browsers (its node js)
         var counter_buffer = new Buffer(octet_array);

         var hash = CryptoJS.HmacSHA1(key,counter_buffer);

         document.write("hex value "+ hash);
         document.write("hash value "+    CryptoJS.enc.Hex.stringify(hash));


AngularJS & Protractor - How to check if elemenent was displayed?


I want to test if my AngularJS app is displaying a loading circle while the app is waiting for a response from a async call.

How can I check is the loading circle is displayed, because expect() seems to be fired when the page is fully loaded.


HTTP POST data not going from AJAX to C# MVC 5 Backend


As the title states, I'm trying to send data from a Javascript frontend to my C# MVC 5 backend, and it doesn't seem to make it. I've run through it with the debugger in Visual Studio and the data I'm trying to pass always ends up null.

Here is my front end code:

var file = $("#my-file").files[0];
file = file[0];
var formData = new FormData();
var MyData = {
    Name: "Form 133",
    Attachments: {
        Type: "Check"
    }
};
formData.append('file', file);
$.ajax({
    type: "POST",
    url: '/NMISProduct/Index',
    contentType: false,
    processData: false,
    data: { formData: formData, MyData: MyData },
    success: function (result) {
        console.log(result);
    },
    error: function (xhr, status, p3, p4) {
        var err = "Error " + " " + status + " " + p3 + " " + p4;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).Message;
        console.log(err);
    }
});

Backend code:

[HttpPost]
public async Task<JsonResult> Index(MyData MyData)
{
    Debug.WriteLine(Request.Params["MyData"]);
    Debug.WriteLine(MyData.Name);
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                var fileName = fileContent.FileName;
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                using (var fileStream = System.IO.File.Create(path))
                {
                    stream.CopyTo(fileStream);
                }
            }
        }
    }
    catch (Exception)
    {
        return Json("Upload failed");
    }
    return Json("File uploaded successfully");
}

public class MyData
{
    public string Name { get; set; }
    public Attachment Attachments { get; set; }
}

public class Attachment
{
    public string Type { get; set; }
}

As I stated, on the Backend MyData always ends up being null. What am I doing wrong?


Python to Javascript JSON objects (Flask)


I am trying to create a simple Flask app where an array of integers is generated on the server and sent to the client. I want to view the array of integers in the console. Here is some sample (working) code in app.py:

from flask import Flask, render_template, request, url_for

import random, json

app = Flask(__name__)

@app.route('/',  methods=['GET'])
def form():
    json_helper = {}
    json_helper['randoms'] = [random.random() for _ in range(40)]
    json_object = json.dumps(json_helper)
    return render_template('sim0625.html', s_data=json_object)

if __name__ == '__main__':
  app.run(debug=True)

And here is a snippet of the Javascript frontend:

<script>

  var data_xyz = {{ s_data|tojson }};

  var JSONObject = JSON.parse({{data_xyz}});
  console.log(JSONObject.randoms);  

 </script>

Unfortunately, none of the javascript works on my webpage, and the error message shown is "Uncaught SyntaxError: Unexpected token u".

Can someone please explain how to fix this? Thanks. My guess is the JSON objects are becoming strings.

Note: The code from the front-end was adapted from this SO question: Extracting data from json object in jQuery or JS


Achieving communication between HighCharts and server.R


I am trying to show a table(or probably another plot) in a separate div element when one of the bars on the HighCharts bar plot is clicked. I am using rCharts from Shiny package to create a HighCharts plot.

In my experimentation till now, I came across two possible psths.

Path 1

I tried to make use of click function in the HighCharts bar/column plot API. I tried doing this.

observe({  
    output$plot <- renderChart2({
                       a <- hPlot(x="id",y="sequence",data=myData,type="column")
                       a$tooltip( animation = 'true', formatter = "#! function() {return '<b>' + 'Frequency of tag_id ' + this.x + '</b>' + ' is ' + this.y;} !#")
                       a$plotOptions(series = list(color = '#388E8E'),column = list(dataLabels = list(enabled = T, rotation = -90, align = 'right', color = '#FFFFFF', x = 4, y = 10),cursor = 'pointer', point=list(events = list(click = func))))
                 return(a)
        }) session$sendCustomMessage(type="data", rg1) )}

and for function func (which is supposed to invoke when a bar is clicked)

func <- "#! function() {
        Shiny.addCustomMessageHandler('data', function(rg1) {
                var data1 = rg1.series            
                $('.container_subcat').highcharts({
                        chart: {
                                type: 'column',
                        }
                        xAxis: { categories:(data1) },
                title: {
                                text: 'Monthly Average Rainfall'
                },
                series: [{  data :(data1)
                        }]
                }); 
})} !#"

I am sure that is not the way to bind data, but I added a lot of code to the above code after looking into several online sources. None of my attempts make me smile. Also, I think if I should proceed in this way, I need to change the data into Java script readable format from R dataframe (rg1 above is a dataframe), but no clue when and where should the conversion be done.

Path 2

I used session$sendCustomMessage() and Shiny.addCustomMessageHandler() functions.

server.R -> app.js

In server.R: observe({ session$sendCustomMessage(type="newdata", data })

In app.js: Shiny.addCustomMessageHandler("newdata", function(data1) { ... });

chart.js -> server.R

In app.js: Shiny.onInputChange("select", this.data.ele);

In server.R: current <- input$select

The above mechanism works fine with all the buttons or other UI elements we have in HTML. But, I am trying to achieve the same mechanism when a bar on the barplot is clicked. I have no clue how to extract each bar from the barplot and use it like we used it in current <- input$select. So, it's basically establishing the communication between the HighCharts UI element(which inturn is shiny/rCharts element) and the server to get the data when an element is clicked.

I came across Shiny input and output bindings and had hard time understanding them and not sure whether they are useful in my particular situation. Can someone walk me through a method/solution which can solve my problem.


What's faster, to hide/show an HTML element, or to delete/insert it?


I am developing a navbar where the selected button is marked by a triangle. Do I put a triangle in every button of my navbar and keep all but one triangle invisible (or visible but same background as the button)? Or do I delete the triangle and reinsert it in the new button?

I understand the performance impact would probably be negligible, but I am learning my ropes, so mostly asking out of curiosity (and wanting to learn the best practices)


Show all data with class same as the id clicked on


I have a question about Jquery. I want to show all data with the same class as I clicked on.

i made a list of things I can click on. So when I click it, the right data should be shown. I made this but it's not working.

This is my Jquery code:

$("div span").hide();
$('input[type=checkbox]').on("change", function(e) {

    var id = $(this).attr('id'); 
    if(this.checked){
        alert("checked");
        e.preventDefault();

    }else{
        alert("not checked");
    }


});

http://ift.tt/1U1nCAn


Inluding variables within partial templates using ejs with express 4.x


I am using Express 4.x with Ejs. I have a main template in which I'd like to include a few partials. I have an array with some objects. Now I want to loop through this array and for each object, I'd like to include a partial that is filled with the values from the object.

This website explains the most of this: http://ift.tt/1CdudwF

Problem is, it includes the partials only, but I want to be able to parse some variables into the partials before including them.

Thanks


Angular get the value the selected for the model.


I got a problem with ng-model and ng-selected. At the beginning the ng-model is null, and the correct value is selected. So if you submit the form you submit a form like this { resolution : undefnied, desiredFps : 30 } and it's incorrect. So I want that the model of the take the value of the selected value designed with ng-selected. What is the correct way of updating the selected value and updating the model with the value as well?

Thanks for you help !

    <form novalidate name="preferencesForm" ng-submit="submitPreferencesForm(BEPreferencesForm)" ng-controller="UserPreferencesFormController">

        <label for="resolution">Choose the resolution : </label>
        <br/>
        <select name="resolution" id="resolution"  ng-model="BEPreferencesForm.resolutionId" ng-change="buttonDisabled = False">
            <option value="1" ng-selected="user.screenWidth ==  800 && user.screenHeight == 600">800x600</option>
            <option value="2" ng-selected="user.screenWidth ==  1024 && user.screenHeight == 768">1024x768</option>
            <option value="3" ng-selected="user.screenWidth ==  1280 && user.screenHeight == 720">1280x720</option>
            <option value="4" ng-selected="user.screenWidth ==  1280 && user.screenHeight == 768">1280x768</option>
            <option value="5" ng-selected="user.screenWidth ==  1360 && user.screenHeight == 768">1360x768</option>
            <option value="6" ng-selected="user.screenWidth ==  1600 && user.screenHeight == 900">1600x900</option>
            <option value="7" ng-selected="user.screenWidth ==  1768 && user.screenHeight == 992">1768x992</option>
            <option value="8" ng-selected="user.screenWidth ==  1920 && user.screenHeight == 1080">1920x1080</option>
        </select>


How can I declare a variable for each object in the JSON file?


I'm new to Javascript. I hope you guys don't mind is my code is a little unorganized.

I have a data.json file that contain 4 objects : a , b , c , d.


Manually

I declared my variables manually.

var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));  


Dynamically

Now, I want to make it dynamically so it can handle all the objects in my JSON file, and it doesn't break - when I add more objects to my JSON file.

So while in the loop, I tried add :

chart[object] = new google.visualization.PieChart(document.getElementById('sa-piechart-'+ data[object] )); // <---- I try to add this line


I got my objects from Ajax call.

var data = {};
var chart = {};

for (var object in objects) {

  var total = objects[object].danger + objects[object].warning + objects[object].success ;


  data[object] = google.visualization.arrayToDataTable([

    ['Piechart' , 'Number of Skills'],
    ['danger'   , ( objects[object].danger/total )  * 100  ],
    ['warning'  , ( objects[object].warning/total ) * 100  ],
    ['success'  , ( objects[object].success/total ) * 100  ],

    ]);

   chart[object] = new google.visualization.PieChart(document.getElementById('sa-piechart-'+ data[object] )); // <---- I try to add this line

}

// var chart_a = new google.visualization.PieChart(document.getElementById('sa-piechart-a'));
// var chart_b = new google.visualization.PieChart(document.getElementById('sa-piechart-b'));
// var chart_c = new google.visualization.PieChart(document.getElementById('sa-piechart-c'));
// var chart_d = new google.visualization.PieChart(document.getElementById('sa-piechart-d'));


Result

I keep getting Uncaught Error: Container is not defined

Any hints / suggestions will be much appreciated !


JQuery: Remove JS after defining event listener but before listener is triggered


I've got a question that searching did not actually yield any results. I apologize if this has been asked in the past.

I'm trying to define an event listener, and immediately remove the JS after defining the event listener. The problem is, I want the removal to take place prior to the event taking placing. Is this possible? I read in the JQuery 1.4 documentation that detach() is like remove, but maintains JQuery data. Is this a viable solution? Are there downsides to removing the code which places an event listener prior to the event taking place?

The reason I'm trying to do this is for a very small amount of added security. Sensitive fields are already masked, no one can gain access to anything sensitive per se. I just have PHP generating a decent amount of JS, and I don't want the temptation of "inspect element". If they do actually see it, it's not a huge deal. I'd just prefer to remove it if possible.

Any help is much appreciated. Thank you in advance.


Google Map takes VERY long to download tiles


I'm having problems with tile downloading in a Google map, with angular-google-maps.

HTTP requests go off as soon as I scroll or zoom, and the download takes milliseconds, but the TIME-TO-FIRST-BYTE delay can go up to several seconds as if the socket was queued for something, somewhere.

  • Rest of site functionality is not affected by the problem
  • Map has around 250 objects (markers, polygons, etc)
  • Map is computationally responsive, interaction is fast
  • Removal of these objects seems to eliminate the problem

A specific client of mine sent a video where it took THREE MINUTES for the tiles to draw on the map. Again, the rest of the site works.

I can reproduce the problem on a smaller time-scale. It's somehow related to objects on the map, but I can't figure out how. What should I do to fix or diagnose this better?


moment: using same parsing format for output format


with libary moment there is option to bring a array of formating options and momentjs use the best match for parsing the input.

for exmaple var date = moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);

but what if I want the take the same format that using in parsing for output formating . var dateText = date.format('selected parse') How I know witch format moment choose to use?


How Javascript Window.open() opens a window in a popup window [duplicate]


This question already has an answer here:

I'm using an ASP.NET C# webform application(.Net 4.5)

And I have a dropdownlist. Whever User make a selection for dropdown list I want a popup windows to show.

Here is my code:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(this.GetType(), "openwindow", "openwindow()", true);
}

and the javascript function is

function openwindow()
{
    window.open('.//Webform1.aspx?CID=1234', '_blank');
}

This code works but instead of poup windows I get new tabs in the same browser window.

How make these new windows pop up instead.


Copying a URL of page X to a readonly text field on page Y


From a webpage www.foo.com, a user clicks a feedback hyperlink to submit feedback about something. It opens a new page with text fields to fill out. What I would like to do is get the URL of the original page www.foo.com for example, to appear in a readonly field on the new page.

This is what I currently have as my test code on my feedback page.

<input id="URL" type="text" name="pageURL" readonly> <script type="text/javascript"> document.getElementById('URL').value = document.location.href; </script>

This displays the URL of the feedback page, page Y, which is what I would expect.

But I'm drawing a blank on how I would get the url of page X, in this example, www.foo.com to appear in the readonly.

I would assume I have to do something in the code for the original page and have that carry over. I do have CORS functioning for other purposes but the information I'm using for that is being brought to a php file instead of the .htm file the form page operates on. I'm still a beginner with CORS but I wouldn't think something like a URL would require it. Or maybe this is mindblowingly simple.


Skip hidden tab indexes


I have the following html:

<span tabindex="19">

</span>

<span tabindex="20">

</span>

<span tabindex="21">

</span>

<span id="hidden" tabindex="22">

</span>

<span tabindex="23">

</span>

<span tabindex="24">

</span>

As you can see one of the span is hidden, the code to hide it is

#hidden
{
display: none;
}

I want a behavior where tab skips the hidden indexes. So i want something like this when i click tab:- go to 19,20,21,23,24

I have no way of controlling the tab indexes as they are coming hard coded in the html i process.


CKEditor Remove (selected) from label on click


I have created a simple plugin to move some of the formatting buttons to a dropdown button. The dropdown button has both an icon and a label. The plugin works as intended except that when clicked on the label shows both the intended text as well as adding "(selected)" to the end.

Here is the button default view (the formatting button):

enter image description here

And here is how it looks when clicked on:

enter image description here

Here is the code for the plugin:

CKEDITOR.plugins.add( 'sf_formatting', {
init: function( editor ) {
     var format = {};
        editor.addMenuGroup( 'format_group' );


        format.indent = {
            label: 'Increase Indent',
            group: 'format_group',
            command: 'indent',
            order: 6
        };

        format.outdent = {
            label: 'Decrease Indent',
            group: 'format_group',
            command: 'outdent',
            order: 7
        };



        editor.addMenuItems( format );

        editor.ui.add( 'Formatting', CKEDITOR.UI_MENUBUTTON, {
            label: 'Formatting',
            // Disable in source mode.
            modes: { 
                wysiwyg: 1 
            },
            icon: 'dropdown',
            onMenu: function() {
                var active = {};

                // Make all items active.
                for ( var p in format )
                    active[ p ] = CKEDITOR.TRISTATE_OFF;
                    return active;
                }
            } ); 
        }
});

I have a second issue

The outdent (decrease indent) only appears when the text has been indented. In the main menu it is always there but greyed out. How can I force the outdent button to always be visible in the dropdown box but not accessible.

Here is a screenshot of the dropdown when the text has been indented:

enter image description here

I'd be really grateful for any help.


Converting images to base64 within a loop before adding to jspdf - javascript


I have researched issues with the base64 conversion and jspdf function quite a bit. ( PS this is my first question on stackoverflow, please bare with any rookie mistakes ).

All seems to work fine with the below code except that the pdf is generated and saved before the loop where the images are converted to base64 and placed to the document is finished. I added a couple alerts to check timing. Would the solution be to check when the loop is finished, the images placed before continuing with the pdf function? if so, how? please help.

$(document).ready(function(){
    $("a#getdoc").click(function(){
    var doc = new jsPDF('landscape, in, legal');
    var myimages = 'img1.jpg|img2.jpg|img3.png';
    var myimgarray = myimages.split('|');

    function convertImgToBase64(url, callback, outputFormat){
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        return canvas.toDataURL("image/jpeg");
        var dataURL = canvas.toDataURL("image/jpeg");
        callback(dataURL);
            canvas = null; 
    }

for(var i = 0; i < myimgarray.length; i++)
{
  icount.count = i;
  var img = new Image();
  alert(checkoutimgarray);

  img.src = '/Portals/0/repair-images/' + myimgarray[i];
  img.onload = function(){
      newData = convertImgToBase64(img);
      alert(newData);
      doc.addImage(newData, 'JPEG', (icount * 100), 10, 70, 15); // would doc be undefined here? out of scope?
  };
}

doc.setFontSize(20);
doc.text(100, 20, "This is a test to see if images will show");
doc.save('My_file.pdf');  

  });
});


jquery tabs function on click


Only problem that i have is when page load, all 4(four) tabs have .current class on it. Want i want is that 1st tab (data-tab="tab-1) have class .current on page load and all other to be hidden. Here is my full project section

$('ul.tabs li').click(function(){
        var tab_id = $(this).attr('data-tab');

        $('ul.tabs li').removeClass('current');
        $('.tab-content').removeClass('current');

        $(this).addClass('current');
        $("#"+tab_id).addClass('current');
    });
.tabs li.current {
  color: red;
}
.tab-content {
  display: none;
 }
.tab-content.current {
  display: block;
}
<script src="http://ift.tt/1oMJErh"></script>
<section class="innovation">
  <div class="categories-wrap">
    <ul class="tabs">
      <li class="tab-link" data-tab="tab-1">
        <i class="sprite-call-black"></i>
        <h4>Pristine coverage</h4>
        <p>Enjoy your calls without interuptions like dropped calls, poor sound quality, and delayed video.</p>
      </li>
      <li class="tab-link" data-tab="tab-2">
        <i class="sprite-call-black"></i>
        <h4>Chat messaging</h4>
        <p>Chat in real time with connections all around the world. </p>
      </li>
      <li class="tab-link" data-tab="tab-3">
        <i class="sprite-call-black"></i>
        <h4>Video calling</h4>
        <p>WiFi paired with reliable cellular service is how we’ve got you covered in more places than ever before.</p>
      </li>
      <li class="tab-link" data-tab="tab-4">
        <i class="sprite-call-black"></i>
        <h4>Photo share</h4>
        <p>WiFi paired with reliable cellular service is how we’ve got you covered in more places than ever before.</p>
      </li>
    </ul>
  </div>
  <div class="tabs-wrap">
    <div id="tab-1" class="tab-content current">
      <img src="" alt="Pristine Coverage">
    </div>
    <div id="tab-2" class="tab-content current">
      <img src="" alt="Chat Messaging">
    </div>
    <div id="tab-3" class="tab-content current">
      <img src="" alt="Video Calling">
    </div>
    <div id="tab-4" class="tab-content current">
      <img src="" alt="Photo Share">
    </div>
  </div>
</section>

Cordova Hybrid App Design - Controllers


I am trying to develop an Application using Cordova framework. My application needs to have many controllers to work. So keeping all the Controllers in the same file will be Bulky as the Code size will increase. So maintainability of the code will be lost.

So for each Controller which Programming Design approach is suggested:

1. Having one main App.js file and writing all the Controllers inside it. And finally importing only App.js file in index.html file.

var myApp = angular.module('myApp', []);

myApp.controller('ControllerA', ['$scope', function($scope) {

}]);

myApp.controller('ControllerB', ['$scope', function($scope) {

}]);

myApp.controller('ControllerC', ['$scope', function($scope) {

}]);

2. Having multiple js files for each controller and importing all in the main index.html file:

Main App.js file:

var myApp = angular.module('myApp', []);

ControllerA.js file:

myApp.controller('ControllerA', ['$scope', function($scope) {

}]);

ControllerB.js file:

myApp.controller('ControllerB', ['$scope', function($scope) {

}]);

ControllerC.js file:

myApp.controller('ControllerC', ['$scope', function($scope) {

}]);


Reduce in Javascript


So I want to convert:

FROM:
{
    emailNotify: {
        EQ: true
    },
    foo: {
        bar: false
    }
}

TO:

Result : [{'condition': 'EQ', 'attribute': emailNotify, 'value': true}, {'condition': 'bar', 'attribute': foo, 'value': false}]

I tried the following code:

var fromObj={
   emailNotify: {
        EQ: true
    },
    foo: {
        bar: false
    }
};


console.log(Object.keys(fromObj));
var result = (Object.keys(fromObj)).reduce(function(p,c,i,a){
    var newObj={};
    newObj["condition"]=Object.keys(fromObj[c])[0];
    newObj["attribute"]=c;
    newObj["value"]=fromObj[c][Object.keys(fromObj[c])[0]];
    p.push(newObj);
    return p;
},[]);


console.log("result", result);

Is this the way you to would do it as well? I believe I'm not using reduce correctly?!

PS: I get the right result! Just wanted to know if it is the elengant way or not?!


Breaking a String Expression and Check for Duplicate


It's JavaScript.

I have a string which is a result of some process:

(A:x OR A:y) AND (B:m)

I want to check for duplication and mark it as duplicate even when the process results in

(A:y OR A:x) AND (B:m)

The process just changed the order of values for A.

P.S: Unfortunately this result is always a string and not some JSON type.

Question: What can be the most efficient solution to check for duplication for the pattern of string mentioned about. split(' ') might work but I am interested in the most efficient possible solution in JS.

  • same letters (e.g. A will have 'OR's b/w there values like 'x' & 'y'above)
  • different letters (e.g. A & B will have 'AND' between them)

Thanks a bunch for looking it.


Object with one key as default (getter/setter)


I know with all the new ECMAScript6 stuff we're having some amazing things happening. My goal was to do something like this I don't know if its possible:

var angEl = {
  get(): blah,
  scope: this.scope(),
  injector: this.injector()
}

Right now I do it like this:

var angEl = blah;
var angElProps = {
  scope: angEl.scope(),
  injector: angEl.injector()
}

Just wondering if there is any cool new hip way to accheive this.


Angularjs Multidimensional array and two relative select boxes


I have a multidimensional array that holds the product names and versions. I want to create an interface that lets the user select the product from a select box, and then the version number in the second select box. The second select box should only show the versions numbers of the product that the user selected in the first select box.

This is my mutidimensional array:

[Object]0: 
         name: "Product 1"
         versions: [Array]0:
                           number: "1.0"
                           number: "1.5.2"
        1: 
         name: "Product 2"
         versions: [Array]0:
                           number: "0.0"
                           number: "0.5"

The user has the option to choose multiple products, so I created an array to hold the users selection.

my controller is setup like this:

app.controller('mainController', function ($scope) {

    $scope.products = [{id: 1, name: '', versions: []}];

  $scope.packages = [];
  $scope.packages[0] = { id: 1, name: 'Product 1', versions: [{number: 1.0}, {number: 1.5}, {number: 2.0}]};
  $scope.packages[1] = { id: 2, name: 'Product 2', versions: [{number: 0.1}, {number: 0.2}, {number: 0.3}]};

    $scope.addProduct = function(){
    var id = $scope.products.length + 1;
    $scope.products.push({id: id, name: "", version: []});

  };
});

And the select boxes are setup like this with angularjs:

    <div  ng-repeat="product in products">
       <label>Product</label>
       <select ng-model="product.product" ng-options="package.name for package in packages" class="form-control"></select>

       <label>Version</label>
       <select ng-model="product.versions" ng-options="version.number for version in product.versions" class="form-control"></select>
</div>
<button ng-click="addProduct()">Add Product</button>

What I tried to do was setup the ng-options to select the versions object of the current product. But this doesn't work.

I created a jsFiddle of what I currently have: http://ift.tt/1U1n0L7

I would really appreciate any suggestions on how to link the version select box with the product selected.

TIA


How can I clone an object and iterate over one of it's properties?


I'm trying to clone an object within a promise and iterate a property of it.

This seems to work, you get an array of objest where page_num is incremented from 2 to 44.

var allOptions = _.map(_.range(2, 45), function(page){
  return { body: { action: 'read', page_num: page, page_size: 5 }}
})

Promise.map(allOptions, function(options){
  return Promise.resolve(options).delay(3000)
}).then(console.log)

However this example above is creating an object from scratch every time.

When I try to clone an existing object like so I get the behavior described below.

var masterOptions = { body: { action: 'read', page_num: 1, page_size: 5 }}

var allOptions = _.map(_.range(2, 45), function(page){
  var options = _.clone(masterOptions)
  options.body.page_num = page
  return options
})

Promise.map(allOptions, function(options){
  return Promise.resolve(options).delay(3000)
}).then(console.log)

or

Promise.map(_.range(2, 45), function(page){
  var options = _.clone(masterOptions)
  options.body.page_num = page
  return Promise.resolve(options).delay(3000)
}).then(console.log)

These do not seem to work, the options object seems to be iterating over the last produced object { body: { action: 'read', page_num: 44, page_size: 5 } } for each iteration.

How can I clone an object and iterate over one of it's properties?


Dynamic Input to Highcharts via HTML input field?


I would like to create a line graph with HighCharts that is able to update with new points via submission through an HTML input field. Any thoughts on how this can be accomplished?

I'm modifying an example given by Highcharts found here: http://ift.tt/1NquFhl

Would something like this work with the input field?

<input id="newPoint" type="text">

var i = 0;
    $('#button').click(function () {
        var chart = $('#container').highcharts();
        chart.series[0].addPoint(50 * (i % 3));
        i += 1;
    });


Debug interface for code wrapped in requireJs


I've got a javascript program apps.js which is loaded in my index.html file like this:

<script data-main='apps.js' src='js/require.js'></script> 

where apps.js is auto-generated code, but includes a requirejs module. I would like to configure a test.html which loads a test.js file after apps.js is loaded. The purpose is that test.js lets me quickly test specific components from apps.js, so I want to treat apps.js as a standalone library.

What are my options?

One option I've found is for test.html to only load test.js in a data-main line, and then test.js to use something like this at its top:

$.ajaxSetup({async:false});
$.getScript("apps.js");
$.ajaxSetup({async:true});

but I'm not sure that's the best approach. Any other ideas? Thanks!


Navbar color change after defined y position


I have a nice navbar that is fixed to the top of the window. When a user scrolls past a certain div, it will change the background color of the navbar. Up to this point, it has been working great for me.

I recently added a few anchor links to my website. Now when a user clicks on an anchor link and is brought to the page with the navbar on it, the navbar is not the correct color. It is only when the user scrolls a little, that the navbar changes color. But I would like the navbar to have the correct background color as soon as the user lands on the page.

$( document ).ready(function() {
var mainbottom = $('.changenavcolor').offset().top +        $('.changenavcolor').height();

// on scroll, 
$(window).on('scroll',function(){

// we round here to reduce a little workload
stop = Math.round($(window).scrollTop());
if (stop > mainbottom) {
    $('.os .navbar').addClass('navbarblue');
} else {
    $('.os .navbar').removeClass('navbarblue');
}

});
});


Running jQuery functions one by one to execute CSS transitions


Here is my fiddle. I would like to achieve 'one page full screen' type of webpage. I have two sections; display one at a time by display:block/none;each section contains content; .content1, .content2 respectively; content div works as a button to fire another section. You can also see a fixed header.

Section .intro contains .content1, section .archive contains .content2.

Now, I would like to build following chain of events on click: (i) .content1 fades out, (ii) .intro gets display:none, .archive gains display:block, (iii) .content2fades in.

The other way around, respectively, on click on .content2: (i) .content2 fades out, (ii) .archive gets display:none, .intro gains display:block, (iii) .content1fades in.

I have some experience with CSS, so I made and checked css transitions for fade in, fade out effects. Up to this point, everything is clear for me.

My problem is, however, I do not know how to build the chains of events. I have googled a lot of similar questions and tried some solutions, but had no luck. I have very little experience with JavaScript, so there might be some obvious mistakes in how I tried to implement the solutions.

I do not attach script in my fiddle; I would like to ask if you could point me in the right direction rather than fix my code, because, you see, I am not sure which solution I should show--so far they all look equally hopeless for me.

Should I go with JavaScript? JQuery? Pure CSS? Could you sketch / write some code how you would handle the problem?

Could you review the idea of displayed/hidden sections for the effect I am trying to achieve?


run javascript after loading data from ajax


index.php

<script type="text/javascript">
$( document ).ready(function() {
   $('[data-countdown]').each(function() {

      var $this = $(this), finalDate = $(this).data('countdown');

      $this.countdown(finalDate, function(event) {

         $this.html('Time Left : '+ event.strftime('%D days %H:%M:%S'))}).on('finish.countdown', function() {

            $this.html('This campaignn has expired!');

          });
     });
 });

</script>

This is javascript used to display countdown timer. I am using jquery.countdown.min.js plugin.

<div class="counter-inner"> <div id="example<?php echo $rec['cid'];?>" data-countdown="<?php echo date("m/d/Y h:i:s", strtotime($rec['Closing_Date']));?>"></div></div><p>

Closing_Date and cid comes from database. When i access it is working fine.

But when i insert data by ajax to index.php. it doesn't do anything. It seems like javascript code is not executed.

I checked in firebug and found date is coming to index.php file but it is not showing countdown timer.

Please advise

Ajax

$(document).ready(function() {
    $('#more').click(function() {
        var get_last_post_display = $('.unique-class:last').attr('id');

        $('#more').html('<img src="ajax-loader.gif"');
        $.post('more_prj.php', 'last_id_post='+get_last_post_display, function(html) {
            if(html) {

                $('#main-div').append(html);
                $('#more').text('Load More Post'); //add text "Load More Post" to button again
            } else {
                $('#more').text('No more Post to load'); // when last record add text "No more posts to load" to button.
            }
        }, 'json');
    });
});


Using Jquery-Raty with Meteor


I am trying to add star ratings populated by a field in my database in a template rendered callback. I believe the problem is that raty can not find the images but I've had trouble getting it to work. The images are currently in App/public/img and the raty code in the callback is:

Template.game.rendered = function() {
$('.game-rating').raty({
    readOnly: true,
    numberMax : 5,
    path: App/public/img,
    score: function() {
        return $(this).attr('data-score');
    },
    starOff: 'star-off.png',
    starOn: 'star-on.png'
});


Ember unable to transition to route


Suppose I was at abc.com/a?id=1 (Transition 1 T1), I want transitionToRoute to make a another full transition to abc.com/a?id=2 (Transition 2 T2).

T1: resolves correctly - a's model correctly in a's router and var t1 = this.transitionToRoute('a',{queryParams:{id:1}}) returns a healty object.

The promise object, below, of the transition dump is: "Router: Settle transition promise when transition is finalized"

Transition {state: TransitionState, intent: C, router: Router, data: Object, resolvedModels: Object…}
 _visibleQueryParams: Objectdata: 
ObjecthandlerInfos: Array[2]
intent: C
isActive: false
params: ObjectpivotHandler: Class
promise: Promise
queryParams: Objectresolve
Index: 1
resolvedModels: Object
router: Router
sequence: 2
state: TransitionState
targetName: "index"

Ok.

Now we are in the route of T1 , so in controller a, we send an action to bubble up to the index main application controller in order to re-transition to a with new set of parameters (T2).

T2: Resolves incorrectly with var t2 = this.transitionToRoute('a',{queryParam:{id:2}}. All parameters are missing objects, the intent is undefined and the promise reads "Router: Transition complete"

Transition {state: TransitionState, intent: undefined, router: Router, data: Object, resolvedModels: Object…}
_visibleQueryParams: Object
data: Object
intent: undefined
params: Object__proto__: Object
promise: Promise_id: 847_label: "Router: Transition complete"_onerror: null_result: TransitionState_state: 1
_subscribers: Array[0]
__proto__: Promisequery
Params: Object
__proto__: Object
__defineGetter__: __defineGetter__() { [native code] }__defineSetter__: __defineSetter__() { [native code] }__lookupGetter__: __lookupGetter__() { [native code] }__lookupSetter__: __lookupSetter__() { [native code] }constructor: Object() { [native code] }hasOwnProperty: hasOwnProperty() { [native code] }isPrototypeOf: isPrototypeOf() { [native code] }propertyIsEnumerable: propertyIsEnumerable() { [native code] }toLocaleString: toLocaleString() { [native code] }toString: toString() { [native code] }valueOf: valueOf() { [native code] }get __proto__: __proto__() { [native code] }set __proto__: __proto__() { [native code] }queryParamsOnly: trueresolvedModels: Object__proto__: Objectrouter: Routerstate: TransitionState__proto__: Object

I totaly don't understand why a second full transition to the same route, fails with changed parameters. I've tried to work around this, but as long as I'm calling the same route, transition objects are the same.

How would you update your model with a new parameter that you set?


Making an Array in chrome.storage and retrieving data


So I'm in a bit of a dillema right now. I can't seem to be able to add an Array in chrome.storage and later retrieving it. Here's the code I have right now:

function() {
    chrome.storage.sync.get({ObjectName: []}, function (result) {
    var ObjectName = result.ObjectName;
    ObjectName.push({ArrayName: document.getElementById("field")});
    });

Now to retrieve it and display it:

chrome.storage.sync.get({ArrayName: function(value) {
            for(i=0; i<value.length; i++) { 
                document.write(value)
            };

The error I am getting, which might be as simple as a syntax issue, amounts to:

Error: Invocation of form get(object) doesn't match definition get(optional string or array or object keys, function callback)


In AngularJS, how can I call a directive inside a controller to perform a task?


I have a controller that performs some DB calls and loads content into my $scope accordingly. Everything works perfect. When the calls are complete I run some JS inside the controller in a call back to adjust the height and other attributes of my application. Unfortunately, I'm running this JS in multiple controllers.

I'd like to place the script into a directive so I can run the directive in the controllers callback and only have the JS live in one spot. Other than this being "the correct way" it will make upkeep much easier.


AngularFire - TypeError: Cannot read property '$add' of undefined


I use Ionic and AngularFire for make a chat, but I have problem: the following error

TypeError: Cannot read property '$add' of undefined at Scope.$scope.sendChat (controllers.js:12)

prevents me to advance in my work. I don't understand where I can found the solution.

This is my code in controller.JS:

angular.module('starter.controllers', ['firebase'])

.factory("Chats", function($firebaseArray) {
  var itemsRef = new Firebase("http://ift.tt/1NquD98");
  return $firebaseArray(chatsRef);
})

.controller('ChatsCtrl', ['$scope', '$rootScope', 
  function($scope, Chats, $rootScope) {

  $scope.sendChat = function(chat) {
      $scope.chats.$add({
        user: 'guest',
        message: chat.message

      });

      chat.message = "";

    };

}])

This is my code in HTML :

<ion-view view-title="Chats">
  <ion-content>
    <div class="list">
      <a class="item item-avatar">
        <img>
        <h2>{{ chat.user }}</h2>
        <p>{{ data.text }}</p>
      </a>
    </div>
    <form>
      <div class="list">
        <div class="item item-input-inset">
          <label class="item-input-wrapper">
            <input type="text" placeholder="Message" ng-model="chat.message">
          </label>
          <button class="button button-assertive ion ion-ios-chatbubble" ng-click="sendChat(chat)"></button>
        </div>
      </div>
    </form>
  </ion-content>
</ion-view>

Can I found a charitable soul to help me?


angularjs shrink down picture from mobile phone


I'm developing a very simple angular app for a tournament were we want to administrate some statistics for the contestants. So far to so good and have it develop with angular and firebase.

Now I want to use picture for the contestants scale it down before converting to Base64 and finally upload it to firebase. I'm using on site my smartphone to take picture from the contestants.

My question is how to scala the down the picture taken by the smartphone down to as small as it possible to see the face and minimise the usage of 3g/4g for my and the user on site.

do you have some experience with that kind of situation? And is this a ok for Firebase to taka long string (I'm quite new to Firebase services)?


OnClientClick triggered when enter pressed in ASP.NET


I have a form with runat="server" and inside it I have two elements :

<form runat="server">
  <asp:Button runat="server" OnClientClick="doSomething();" />
  <asp:TextBox runat="server" Text="hello" />
</form>

My problem is when I press enter while the cursor inside the textbox the doSomething function runs. What can I do to prevent this?


Attaching an image to a randomly generated number between 1-10?


I'm fairly new to HTML and I'm able to successfully generate the random numbers, but I want to attach an image to a specific number E.G a card game (11 =jack =12=queen ..etc)

This is what I have

function numbers() {
    var x = Math.floor((Math.random() * 10) + 1);
    var img = document.createElement("img");
    if(x ==1||2||3||4||5||6||7) {
        img.src = "ace.jpg";
    }
    document.getElementById("num").innerHTML = "Rule " + x;
}


user can't change select option on populated angular windows opoup


I have angular js popup on my application when user click edit it repopulate the popup form and user change/update popup form my problem with select option because it won't work when user change his selection and click edit

    <script type="text/ng-template" id="ActivitiesModalEdit.html">
        <div class="modal-header">
            <h3 class="modal-title">Edit Activity</h3>
        </div>
        <div class="modal-body">
            <div class="panel-warning" data-ng-show="isValidationVisible()">
                <div class="panel-heading-warning"><i class="icon-alert"></i>Required Items</div>
                <div class="panel-body-warning">
                    <div data-ng-show="displayModel.showActivityValidator">Activity Required</div>
                    <div data-ng-show="displayModel.showReasonValidator">Reason Required</div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <label class="" id="lblActivityValue"><i class="icon-required"></i>Activity</label>
                    <p>
                        <select class="dropdownbox" data-ng-model="model.activityId" data-ng-options="item.recordId as item.name for item in activityTypes"></select>
                    </p>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <label class="" id="lblTimeSpentInMinutesValue">Time Spent</label>
                    <p>
                        <input kendo-numeric-text-box k-min="0" data-ng-model="model.timeSpentTimeHour" k-max="24" type="number" k-options="timeSpentSpinnerOptHour" />
                        <input kendo-numeric-text-box k-min="0" data-ng-model="model.timeSpentTimeMinute" k-max="59" type="number" k-options="timeSpentSpinnerOptMin" />
                        <span style="display: none;">{{calculateTimeSpent(model.timeSpentTimeHour,model.timeSpentTimeMinute)}}</span>
                    </p>
                </div>
                <div class="col-md-9">
                    <label class="" id="lblFiller">&nbsp</label>
                    <div class="well-time">{{model.timeSpent | formatTimeFromMinutes}}</div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <label class="" id="lblKilometersTravelledValue">Kilometers Travelled</label>
                    <p>
                        <input kendo-numeric-text-box k-min="0" k-max="1000" k-ng-model="model.kilometers" k-options="distanceSpinnerOpt" />
                    </p>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label id="lblReason" for="txtReason"><i class="icon-required"></i>Reason</label>
                        <br />
                        <input class="form-control" data-ng-model="model.reason" maxlength="500" />
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary" data-ng-click="ok(model)">Edit</button>
            <button class="btn btn-warning" data-ng-click="cancel()">Close</button>
        </div>
    </script>

var app = angular.module('app');

var NonPatientActivitiesEditController = function ($scope, $modalInstance, selectedItem, valuesService) {

    $scope.model = nonpatientDetailModel();

    $scope.model.activity = selectedItem.activity;
    $scope.model.activityId = selectedItem.activityId;
    $scope.model.timeSpentTimeHour = Math.floor( selectedItem.timeSpent / 60 );
    $scope.model.timeSpentTimeMinute = selectedItem.timeSpent % 60;
    $scope.model.timeSpent = selectedItem.timeSpent;
    $scope.model.kilometers = selectedItem.kilometers;
    $scope.model.reason = selectedItem.reason;


    $scope.displayModel = nonpatientDetailDisplayModelTemplate();



    var errorHandler = function (reason) {
        toastr[error](reason);
    };


    $scope.distanceSpinnerOpt = {
        format: '# km'
    };

    $scope.ok = function (model) {
        var validator = nonpatientDetailsValidator($scope);
        if (validator.valid()) {
            $modalInstance.close({ kilometers: model.kilometers, reason: model.reason, activityId: model.activityId, timeSpent: model.timeSpent });
        } else {
            validator.addWatches();
        }
    };
    $scope.isValidationVisible = function () {
        return $scope.displayModel.showActivityValidator ||
            $scope.displayModel.showReasonValidator;
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    valuesService.getFormId('nonPatientForm')
        .then(function (formId) {

            getFieldValues(formId, 'nonPatientFormActivities').then(function (data) {
                $scope.activityTypes = data;
            });
        }, errorHandler);
    var getFieldValues = function (formId, fieldName) {
        return valuesService.getFieldId(formId, fieldName)
            .then(function (data) {
                var fieldId = data;
                return valuesService.getValues(formId, fieldId);
            }, errorHandler);
    };

    var timeSpin = function () {
        $scope.model.timeSpent = this.value();
    };

    $scope.timeSpentSpinnerOptMin = {
        spin: timeSpin,
        format: '# Minute'
    };
    $scope.timeSpentSpinnerOptHour = {
        spin: timeSpin,
        format: '# Hour'
    };
    $scope.calculateTimeSpent = function (hour, minute) {
        var result = (hour * 60) + minute;
        $scope.model.timeSpent = result;
    }
};

app.controller('NonPatientActivitiesEditController', ['$scope', '$modalInstance', 'valuesService', NonPatientActivitiesEditController]);


adapt an activity to a fragment


i'm newbie in android developing, i'm trying to adapt this guide to my application, i've got an activity that manages 5 tabs, and i want to display in the first tab the activity in the guide.. here is what i tried but it gives me an error:

public class SampleFragment extends Fragment {


    public static String KEY_ID = "id";
    public static String KEY_EMAIL = "email";
    public static String KEY_NAME = "name";
    public static String KEY_JSON = "JSON_DB";

    //EVENTI
    private static final String TAG = SampleActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://ift.tt/1p6F7Tc";
    //EVENTI

    private static final String ARG_POSITION = "position";
    private WebView myWebView;

    public ValueCallback<Uri> mUploadMessage;
    public final static int FILECHOOSER_RESULTCODE = 1;

    private int position;


    public static SampleFragment newInstance(int position) {
        SampleFragment f = new SampleFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);

        return f;
    }

    public class MyWebChromeClient extends WebChromeClient {
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), SampleFragment.FILECHOOSER_RESULTCODE);

        }
    }
        public class myWebClient extends WebViewClient {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url));
                    startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LoadPreferences();

        Log.i("string", KEY_EMAIL);
        Log.i("string", KEY_ID);
        Log.i("string", KEY_NAME);
        Log.i("string", KEY_JSON);

        position = getArguments().getInt(ARG_POSITION);

        View rootView = inflater.inflate(page, container, false);

        Activity activity = getActivity();
        if (KEY_ID == "0") {

            Toast.makeText(activity, "Non essendo connesso a Facebook non potrai usufruire di tutte le funzionalità che abbiamo creato apposta per te.", Toast.LENGTH_LONG).show();
        }



            switch (position) {
                case 0:
                    Cache cache = App.getInstance().getRequestQueue().getCache();
                    Cache.Entry entry = cache.get(URL_FEED);
                    if (entry != null) {
                        // fetch the data from cache
                        try {
                            String data = new String(entry.data, "UTF-8");
                            try {
                                parseJsonFeed(new JSONObject(data));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    } else {
                        // making fresh volley request and getting json
                        JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
                                URL_FEED, null, new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                VolleyLog.d(TAG, "Response: " + response.toString());
                                if (response != null) {
                                    parseJsonFeed(response);
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                VolleyLog.d(TAG, "Error: " + error.getMessage());
                            }
                        });

                        // Adding request to volley request queue
                        App.getInstance().addToRequestQueue(jsonReq);
                    }







                    break;
                case 1:



                    break;
                case 2:



                    break;
                case 3:



                    break;

                case 4:

                   break;
            }

       // }



        return rootView;
    }



    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj.getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CallbackManager callbackManager = CallbackManager.Factory.create();
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


        private void LoadPreferences(){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        KEY_NAME = sharedPreferences.getString("name", "0") ;
        KEY_EMAIL = sharedPreferences.getString("email", "0") ;
        KEY_ID = sharedPreferences.getString("id", "0") ;
        KEY_JSON = sharedPreferences.getString("JSON_DB", "0") ;
        //Toast.makeText(this, name, Toast.LENGTH_LONG).show();
        //Toast.makeText(this, id, Toast.LENGTH_LONG).show();
        //Toast.makeText(this, email, Toast.LENGTH_LONG).show();
    }



}

and here is the error:

06-29 19:49:53.183  13763-13763/com.tekinarslan.material.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.tekinarslan.material.sample.SampleFragment.parseJsonFeed(SampleFragment.java:244)
            at com.tekinarslan.material.sample.SampleFragment.onCreateView(SampleFragment.java:150)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:16419)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16419)
            at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:851)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2549)
            at android.view.View.measure(View.java:16419)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2188)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1333)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1544)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1230)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5093)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
            at android.view.Choreographer.doCallbacks(Choreographer.java:591)
            at android.view.Choreographer.doFrame(Choreographer.java:561)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5283)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

EDIT Ok, i instantiate and it works, but it doesn't display me the status..