mercredi 1 juillet 2015

Single page applications and elements

Are there still any benefits of using a <form> element instead of let's say a <div> element in the context of a single page application? The purpose of the <form> element makes sense to me if the "form" submission isn't made with an ajax call (I'm talking about the more traditional way of submitting a form, with a input/button of type "submit" and the action attribute of the form element that describes the url to call), but otherwise I do not see it's utility (maybe for search engines?).

Copy multiple input fields to other matching input fields with jQuery/Javascript

I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form. The dummy fields will have the same names as the real form (so I can match them up).

So in dummy form:

<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />

and in real form:

<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />

I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object. Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)

I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.

var inputValues = [];
    $("#dummyForm input").each(function() {
        inputValues.push($(this).val());
    });

Any help or advice much appreciated.

Creating closures in loops

I am learning about closures and have the basics on what they are and how they work.

I got the following code from MDN and know what the solution is since it's in the same article. I just don't get how this is possible:

<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>


function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}


function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}

setupHelp();

I know the section of code that needs change for this to work is:

document.getElementById(item.id).onfocus = function() {

      showHelp(item.help);

    }

How is it that at the end of the loop the text being pointed to is: Your age (you must be over 16) for all elements?

I can follow the code and see that the loop successfully loops through the elements correctly but I can't get my head around how is it that the last item pointed to for all elements at the end is Your age ... since it saves each one individually with the onfocus = funtion()... and what ever item.help is at the time is passed in and saved.

Any step by step explanation would greatly help in me understanding what is going on.

Can't use this to point a selected element with jQuery

Why this JS does not apply my class to the element please ?

<input type="password" name="customer-new-password" class="form-control">

<script>
if($("input[name='customer-new-password']").val()=='') {
    $(this).addClass('required');
}
else {
    $(this).removeClass('required');
}
</script>

Thanks.

Javascript conflicting with html anchor

I'm currently creating a website which has a persistent header and footer. To cut down on code duplication, I use jquery to load the header.html and footer.html when each different page is loaded.

Each html page which uses this header and footer, loads it with the code below.

<!-- Header and footer loading -->
<script> 
  $(function() {
    $("#header").load("header.html"); 
    $("#footer").load("footer.html");
  });
</script>

<div id="header">
  (header.html content rendered here)
</div>

The best way to explain this next part is by going to the site I have linked. What I would like to do is have the drop down button take a user to the specific section of the equipment page from any other page on the website. As you can currently see, this function only works if the user is already on the equipment page.

From everything I've read, cross page anchors should be setup the same way as in-page anchors. Use <a href="equipment.html#anchorname></a> and then link it to the page with <a id="anchorname></a>. However, this approach is only working when the user is on the same page as the anchor. I'm pretty sure this is due to the timing of anchor mechanism and when the jQuery code runs.

My two questions are...

  1. Could someone explain the sequence of events that are taking place which are causing my anchor not to work.
  2. What do I need to do in order to get my cross-site anchors to work properly?

Thanks and let me know if you need specific code snippets or have any questions.

Making carousel, can't scroll after click function animates (JSFiddle link updated)

Problem

I'm trying to make a carousel, so when a person clicks the back arrow the page .animate and scrolls back up to the previous chapter in the story. However, after this happens the page appear to get stuck and I can't scroll anymore. I'm wondering why this is happening?

Update #2 - JSFiddle updated: http://ift.tt/1H1tZwF

$(function(){

    /* -------------------------------------
    GLOBAL VARIABLES
    --------------------------------------*/

    var nav = 72.5;
    var splash = 750 + nav;
    var one = $(".one").offset().top - nav;
    var two = $(".two").offset().top - nav;
    var three = $(".three").offset().top - nav;
    var four = $(".four").offset().top - nav;
    var five = $(".five").offset().top - nav;

    /* -------------------------------------
    PROGRESS BAR
    --------------------------------------*/
    $(window).scroll(function(){
        var scroll = $(window).scrollTop();
        var documentHeight = $(document).height();
        var windowHeight = $(window).height();
        var scrollPercent = (scroll / (documentHeight - windowHeight)) * 100;
        var position = scrollPercent;
        $("progress").attr("value", position);

        /* -------------------------------------
        CHAPTER TEXT SWITCHING
        --------------------------------------*/
        if (scroll >= one && scroll <= two) {
            $(".title").html("Chapter 1");
        } else if (scroll >= two && scroll <= three) {
            $(".title").html("Chapter 2");
        } else if (scroll >= three && scroll <= four) {
            $(".title").html("Chapter 3");
        } else if (scroll >= four && scroll <= five) {
            $(".title").html("Chapter 4");
        } else if (scroll >= five) {
            $(".title").html("Chapter 5");
        } else {
            $(".title").html('It could have been me');
        };

        /* -------------------------------------
        ARROW CAROUSEL
        --------------------------------------*/

        $(".backward").click(function(){
            if (scroll >= two && scroll <= three) {
                $("body").animate({
                    scrollTop: $(".one").offset().top - splash
                }, 1000);
            } else {
                console.log("Backward");
                // $("html, body").animate({
                //  scrollTop: $(".two").offset().top
                // }, 1000);
            }

        });

        $(".forward").click(function(){
            console.log("Forward");
        });
    })
});

index.html

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="UTF-8">
    <title>Name of Website</title>
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="http://ift.tt/18QXBAt">
    <link href='http://ift.tt/YW5hLg' rel='stylesheet' type='text/css'>
    <!-- <link rel="icon" type="image/png" href="assets/img/favicon.ico"> -->
</head>
<body>

    <nav>
        <progress value="0" max="100"></progress><!-- /.progress -->
        <div class="logo">
            <img src="assets/img/logo.png" alt="" class="bdnsun">
        </div><!-- .logo -->

        <div class="details">
            <p class="title">'It could have been me'</p>
            <span class="dot first">&#9679;</span>
            <span class="by">By</span>
            <span class="byline">Nancy MacDonald</span>
            <span class="dot second">&#9679;</span>
            <span class="time">Time to Read:</span>
            <span class="full">19 min</span>
        </div><!-- .details -->

        <div class="social">
            <a href=""></a>
            <a href=""></a>
            <a href=""></a>
        </div><!-- .social -->

        <div class="chapters">
            <div class="backward" id="target" title="Previous chapter"><i class="fa fa-angle-left fa-4x"></i></div><!-- /.backward -->
            <div class="forward" title="Next chapter"><i class="fa fa-angle-right fa-4x"></i></div><!-- /.forward -->
        </div><!-- .chapters -->
    </nav>

    <main>
        <div class="splash" id="top">
            <div class="teaser">
                <h1>'It could have been me'</h1>
                <p class="subhead">Thirteen women share their remarkable stories</p>
                <p class="byline-alt">Nancy MacDonald</p>
            </div><!-- .splash -->
        </div>

        <div class="wrapper">
            <div class="chapter one">
                <p>Wolf kale chips stumptown fanny pack, vegan kogi asymmetrical. Locavore polaroid sustainable Blue Bottle, farm-to-table kogi plaid keytar Tumblr occupy gluten-free. Pitchfork shabby chic lo-fi flannel, bitters hella readymade. Ethical meggings master cleanse Schlitz mustache Blue Bottle, <span class="highlight">American Apparel</span> dreamcatcher vinyl Tumblr. Scenester try-hard Portland master cleanse. Skateboard tofu mumblecore, swag retro aesthetic kale chips American Apparel lo-fi normcore bespoke Helvetica synth. Tousled Brooklyn DIY, quinoa Etsy chambray umami.</p>

                <p>Meh literally freegan, church-key Tumblr sustainable mlkshk sriracha Pitchfork. Migas stumptown deep v lumbersexual. Cray roof party skateboard scenester hashtag, plaid distillery wayfarers banjo ethical artisan. Skateboard irony Portland deep v, cliche DIY Pinterest brunch Echo Park tilde Helvetica. Etsy stumptown chambray craft beer four loko brunch, twee mustache. Crucifix yr synth, irony mlkshk polaroid master cleanse iPhone mixtape twee direct trade keytar. Brooklyn Pinterest migas Portland gluten-free.</p>

                <blockquote>
                    <span class="quote">“</span>
                    Meh literally freegan, church-key Tumblr sustainable mlkshk sriracha Pitchfork. Migas stumptown deep v lumbersexual.
                </blockquote>

                <p>Blog cold-pressed vinyl Shoreditch organic put a bird on it. Salvia put a bird on it swag chillwave Bushwick, fanny pack stumptown art party selvage narwhal. Readymade distillery asymmetrical bespoke. Blue Bottle bitters tofu, Austin retro meh gentrify tattooed American Apparel Banksy. Try-hard whatever pug tousled DIY lomo. Marfa pop-up shabby chic messenger bag Intelligentsia. Kale chips gastropub viral, Helvetica forage disrupt mumblecore mlkshk Brooklyn vegan.</p>
            </div><!-- .chapter -->

            <div class="chapter two">
                <p>Chapter 2</p>
            </div><!-- .chapter -->

            <div class="chapter three">
                <p>Chapter 3</p>
            </div><!-- .chapter -->

            <div class="chapter four">
                <p>Chapter 4</p>
            </div><!-- .chapter -->

            <div class="chapter five">
                <p>Chapter 5</p>
            </div><!-- .chapter -->
        </div><!-- /.wrapper -->
    </main>

    <p class="more">Read More</p>

    <footer>
    </footer>

    <script src="http://ift.tt/1JsU1tb"></script>
    <script src="http://ift.tt/1CWMYDx"></script>
    <script src="assets/js/scripts.js"></script>

</body>
</html>

WebRTC renegotiate the Peer Connection to switch streams

I have this script where. two users can chat using webrtc. when two users enter to the chat room . the text chat is started automatically. I want to add a botton to allow video chat. for example there is two users. user_1 and user_2 when they enter to the chat room, the text chat is initiated, they can send text messages to each others, and when user_1 click on the video icon the user_2 can see user_1. and the same thing with the user_2 when he click on video icon. This is the code i'm using now. but this code doesn't work properly, when i stat chatting with someone and i click on video icon i can see my self but the other user can't see me.I didn't post all the code because it's more than 300 lines, but i think you cant help me to modify just this to make it work, and thanks in advance everyone.

var pc_config = webrtcDetectedBrowser === 'firefox' ?
{'iceServers':[{'url':'stun:23.21.150.121'}]} : // IP address
{'iceServers': [{'url': 'stun:stun.l.google.com:19302'}]};
var pc_constraints = {
  'optional': [
    {'DtlsSrtpKeyAgreement': true},
    {'RtpDataChannels': true}
  ]};
var sdpConstraints = {'mandatory': {
  'OfferToReceiveAudio':true,
  'OfferToReceiveVideo':true }};
var constraints = {video: true, audio: true};
var v_on_off = false;
v_call.on('click', function(){
  if (!v_on_off) {
        navigator.getUserMedia(constraints, handleUserMedia, handleUserMediaError);
        if (isInitiator) {
            maybeStart();
        };
      v_on_off = true;
  } else {
      // stop stream
  }
});
function handleUserMedia(stream) {
        localStream = stream;
        attachMediaStream(localVideo, stream);
        sendMessage('got user media');
}
var socket = io.connect();
if (room !== '') {
  socket.emit('create or join', room);
}
socket.on('created', function (room){
  isInitiator = true;
});
socket.on('join', function (room){
  isChannelReady = true;
});
socket.on('joined', function (room){
  isChannelReady = true;
});
function sendMessage(message){
  socket.emit('message', message);
}
// this will start a text chat between too peers
sendMessage('got user media');
if (isInitiator) {
    maybeStart();
  }
socket.on('message', function (message){
  console.log('Received message:', message);
  if (message === 'got user media') {
    maybeStart();
  } else if (message.type === 'offer') {
    if (!isInitiator && !isStarted) {
      maybeStart();
    }
    pc.setRemoteDescription(new RTCSessionDescription(message));
    doAnswer();
  } else if (message.type === 'answer' && isStarted) {
    pc.setRemoteDescription(new RTCSessionDescription(message));
  } else if (message.type === 'candidate' && isStarted) {
    var candidate = new RTCIceCandidate({sdpMLineIndex:message.label,
      candidate:message.candidate});
    pc.addIceCandidate(candidate);
  } else if (message === 'bye' && isStarted) {
    handleRemoteHangup();
  }
});
function maybeStart() {
  if (!isStarted && isChannelReady) {
    createPeerConnection();
    isStarted = true;
    if (isInitiator) {
      doCall();
    }
  }
}
function createPeerConnection() {
  try {
    pc = new RTCPeerConnection(pc_config, pc_constraints);
    if (typeof localStream != 'undefined') {
        pc.addStream(localStream);
    }
    pc.onicecandidate = handleIceCandidate;
  } catch (e) {
    alert('Cannot create RTCPeerConnection object.');
      return;
  }
  pc.onaddstream = handleRemoteStreamAdded;
  pc.onremovestream = handleRemoteStreamRemoved;
  if (isInitiator) {
    try {
      // Reliable Data Channels not yet supported in Chrome
      sendChannel = pc.createDataChannel("sendDataChannel",
        {reliable: false});
      sendChannel.onmessage = handleMessage;
      trace('Created send data channel');
    } catch (e) {
      alert('Failed to create data channel. ' +
            'You need Chrome M25 or later with RtpDataChannel enabled');
      trace('createDataChannel() failed with exception: ' + e.message);
    }
    sendChannel.onopen = handleSendChannelStateChange;
    sendChannel.onclose = handleSendChannelStateChange;
  } else {
    pc.ondatachannel = gotReceiveChannel;
  }
}
function gotReceiveChannel(event) {
  trace('Receive Channel Callback');
  sendChannel = event.channel;
  sendChannel.onmessage = handleMessage;
  sendChannel.onopen = handleReceiveChannelStateChange;
  sendChannel.onclose = handleReceiveChannelStateChange;
}
function handleSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  enableMessageInterface(readyState == "open");
}
function handleReceiveChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Receive channel state is: ' + readyState);
  enableMessageInterface(readyState == "open");
}
function handleIceCandidate(event) {
  console.log('handleIceCandidate event: ', event);
  if (event.candidate) {
    sendMessage({
      type: 'candidate',
      label: event.candidate.sdpMLineIndex,
      id: event.candidate.sdpMid,
      candidate: event.candidate.candidate});
  } else {
    console.log('End of candidates.');
  }
}
function doCall() {
  var constraints = {'optional': [], 'mandatory': {'MozDontOfferDataChannel': true}};
  // temporary measure to remove Moz* constraints in Chrome
  if (webrtcDetectedBrowser === 'chrome') {
    for (var prop in constraints.mandatory) {
      if (prop.indexOf('Moz') !== -1) {
        delete constraints.mandatory[prop];
      }
     }
   }
  constraints = mergeConstraints(constraints, sdpConstraints);
  console.log('Sending offer to peer, with constraints: \n' +
    '  \'' + JSON.stringify(constraints) + '\'.');
  pc.createOffer(setLocalAndSendMessage, null, constraints);
}
function doAnswer() {
  console.log('Sending answer to peer.');
  pc.createAnswer(setLocalAndSendMessage, null, sdpConstraints);
}
function handleRemoteStreamAdded(event) {
  console.log('Remote stream added.');
  attachMediaStream(remoteVideo, event.stream);
  remoteStream = event.stream;
}  

and this is a server side code :

socket.on('message', function (message) {
    // channel-only broadcast...
    socket.broadcast.to(message.channel).emit('message', message);
});
// Handle 'create or join' messages
socket.on('create or join', function (room) {
    var numClients = io.sockets.clients(room).length;
    // First client joining...
    if (numClients == 0){
        socket.join(room);
        socket.emit('created', room);
    } else if (numClients == 1) {
        io.sockets.in(room).emit('join', room);
        socket.join(room);
        socket.emit('joined', room);
    } else { 
    socket.emit('full', room);
    }
});

How to concatenate 3 dynamic value text boxes and move them to clipboard

sas per my title i'm trying to concatenate 3 textboxes that have dynamic values based on radio button presses. I'm very new to HTML and Java so have literally been self teaching off google to come up with this so it's probably messy. The code so far is as follows:

http://ift.tt/1H1tXFb

<input type="radio" name="r3" onclick="myFunction2(this.value)" value="CA$!">Only want to talk to case owner<br>
<input type="radio" name="r3" onclick="myFunction2(this.value)" value="VO$!">Transfer to Voicemail<br> 
<input type="radio" name="r3" onclick="myFunction2(this.value)" value="EM$!">No EOS entry required<br>

<input type="radio" name="r3" onclick="myFunction2(this.value)" value="NA$!">N/A<br><br>
<input type="text" id="result2">

  </form>

Here is just a small exerpt of how 1 part of the code works. The rest is in the jsfiddle.

I've tried referencing the ID with Javascript but it won't update so I think i'm getting the syntax wrong. This is all being done in notepad (not access to notepad++ or anything better)

Thank you very much, please let me know if I can provide more information.

How to write a obfuscater for javascript code?

I want to write a program that scans javascript code, and replace variable names with short, meaningless identifiers, without breaking the code.

I know YUI compresser and google's closure compiler can do this. I am wondering how can I implement this?

Is it necessary to build the abstract syntax tree? If not, how can I find the candidate variables for renaming?

How to hide html items with a radio button

This is a beginner html/css/javascript question. I've been beating my head against a wall, but still can't figure this out. I have a simple web form that users fill out(name, email, etc) and the way it's supposed to work is that when the user clicks a radio button that says "Yes" they see a drop down menu with a set number of items and when they click "No" they see a text field. I have this part working correctly, but I want the drop down menu and text field to start hidden, and then appear when the yes or no radio button is clicked. I've tried style = display:hidden; but when I used this the text and drop-down menu wouldn't appear anymore.

Thanks so much for any answers!

This is the code I'm using:

<tr align="left" valign="middle">
  <td colspan="1" rowspan="1">
    <p>&nbsp;</p>
  </td>
  <td colspan="1" rowspan="1">
    <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
  </td>
  <td colspan="1" rowspan="1">
    <p>Do you own a Zaxwerks product?</p>
  </td>
  <td colspan="1" rowspan="1">
    <p><input id="customer" name="STATUS" onclick="javascript: test();" type="radio" value="Existing Customer" /> Yes<br />
    <input id="demo" name="STATUS" onclick="javascript: test();" type="radio" value="Downloaded Demo" /> No</p>
  </td>
  <script type="text/javascript"> 
    function test() {
      if (document.getElementById('customer').checked) {
        //Show
        document.getElementById('show_customer').style.display = 'block';
        document.getElementById('show_customer2').style.display = 'block';
        document.getElementById('show_customer3').style.display = 'block';
        document.getElementById('show_customer4').style.display = 'block';

        //Hide
        document.getElementById('show_demo').style.display = 'none';
        document.getElementById('show_demo2').style.display = 'none';
        document.getElementById('show_demo3').style.display = 'none';
      } else {
        //Show
        document.getElementById('show_demo').style.display = 'block';
        document.getElementById('show_demo2').style.display = 'block';
        document.getElementById('show_demo3').style.display = 'block';

        //Hide
        document.getElementById('show_customer').style.display = 'none';
        document.getElementById('show_customer2').style.display = 'none';
        document.getElementById('show_customer3').style.display = 'none';
        document.getElementById('show_customer4').style.display = 'none';
      }
    }
  </script>
  <td>&nbsp;</td>
</tr>
<tr>
  <td colspan="1" rowspan="1" style="display: none;">
    <p>&nbsp;</p>
  </td>
  <td colspan="1" rowspan="1" style="display: none;">
    <div id="show_customer">
      <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
    </div>

    <div id="show_demo" style="display: none;">
      <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
    </div>
  </td>
  <td colspan="1" rowspan="1" style="display: none;">
    <div id="show_customer2">
      <p>Product Owned:</p>
    </div>

    <div id="show_demo2" >
      <p>Where did you hear about us?:</p>
    </div>
  </td>
<!--This is where the user selects which product they own. (In the following code: value equals "what appears in the log file" what appears in the site menu)-->
  <td colspan="1" rowspan="1">
    <div id="show_customer3" style="display: none;">
      <p><select id="WHAT" name="WHAT" size="1">
        <option selected="selected" value="">Select One</option>
        <option value="Item 1">Item 1</option>
        <option value="Item 2">Item 2</option>
        <option value="Item 3">Item 3</option>
        <option value="Item 4">Item 4</option>
        <option value="Item 5">Item 5</option>
        <option value="Item 6">Item 6</option>
        <option value="Item 7">Item 8</option>
        <option value="Item 9">Item 9</option>
        <option value="Item 10">Item 10</option>
        <option value="Item 11">Item 11</option>
        <option value="Item 12">Item 12</option>
      </select></p>
    </div>

    <div id="show_demo3" style="display: none;">
      <p>
        <input maxlength="64" name="WHERE" size="30" type="text" value="" />
      </p>
    </div>
  </td>
  <td>&nbsp;</td>
</tr>

String split with RegExp returns empty strings at either end

// pattern -- <some name with an optional 1/2/3 at end separated by a _>
var re = new RegExp("^\(.*\)_\([1-3]\)$")
"".split(re) 
// returns [""] --- OK
"abc_d_4".split(re) 
// returns ["abc_d_4"] --- OK
"abc_d_3".split(re)
// returns ["", "abc_d", "3", ""] --- WHOA! hoped-for was ["abc_d", "3"]
// similarly, "_3".split(re), "abc_d_3_4_3".split(re)

why the extra empty strings at either end in the last case, and how to avoid that? I would definitely appreciate an explanation.

I can see similar questions have been asked before on SO but not this case (or pl point me there)

Jquery Sometime Working fine and sometime giving "Uncaught TypeError: undefined is not a function"

Here is my script tag

Sometime It loaded all the pages, sometime few and giving the following error: Uncaught TypeError: undefined is not a function

Earlier I searched on the web about the same error, someone suggested to use jQuery.noConflict(),jQuery.noConflict(true)

I stored the value of jquery no conflict int a variable named j and replaced the jquery sign($) with j, but it didn't work. Also tried with passing a true value to no conflict as suggested by someone else on the forums, but no solution the problem.

Any help appreciated!

<script>
    //var j = jQuery.noConflict(true);
    $(document).ready(function () {
        $('#loading_status').hide();
        var total_row =946;
        var per_page = 15;
        var total_page = parseInt(total_row / per_page);

        var current_page = 0;
        var loadable = true;

        var loadNextPage = function (start, rows) {
            $('#loading_status').show();
            $.ajax({
                url: 'http://ift.tt/1dz7kgE',
                type: 'post',
                data: {
                    page: 0,
                    start: start,
                    records: rows
                },
                success: function (result) {
                    $("#flushed").append(result);
                    loadable = true;
                    $('#loading_status').hide();
                },
                error: function (xhr, status, error) {
                    alert("Error code: " + xhr.status + "\n\n\nError message: " + xhr.responseText);
                }
            });
        };

        loadNextPage(current_page, per_page);

        $(window).scroll(function () {
            if (($(window).scrollTop() + $(window).height()) >= ($(document).height() - 1000) && current_page < total_page && loadable == true) {
                loadable = false;
                current_page++;
                var start = (current_page * per_page) + 1;
                loadNextPage(start, per_page);
            }
        });

    });
</script>

Find polygon for place in KML

NOTE: Please make sure you read my updates at the bottom!!


I have a KML file that I load 'onto' a Google Map; I also have a searchbox where users can search for a city. When the city is found I place a marker which, in most (if not all) cases should fall in one of the polygons defined in the KML.

I can click a polygon and it shows an info-popup with the areacode for that area; however: when a marker is placed I would like to have this info-popup shown automatically (and possibly other(s) that are shown before placing the marker hidden).

I have looked over the Maps V3 documentation but was unable to find anything. Is this possible?

You can view the project at http://ift.tt/1f38EtI, the source can be found at http://ift.tt/1dz7lRG

The relevant (snippet of) code is:

google.maps.event.addListener(autocomplete, 'place_changed', function () {
    var place = autocomplete.getPlace();
    if (!place.geometry)
        return;

    // Remove any existing markers
    for (var i = 0, marker; marker = markers[i]; i++)
        marker.setMap(null);
    markers = [];

    // Create a marker for place.
    var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
    });
    markers.push(marker);

    // ... Here I should figure out in which polygon the marker is positioned
    // ... and preferrably open/display the info-window which is shown when a
    // ... polygon is clicked.

    // Scroll (pan) to marker
    map.panTo(place.geometry.location);
});

Also, as a side-question: autocomplete.getPlace(); always returns an object; what is the best way to find out if the object is an actual (useful) place? When I search for xxxx for example, getPlace() returns Object {name: "xxxx"}, an actual result (like searching for Amsterdam) returns Object {address_components: Array[4], adr_address: "<span class="locality">Amsterdam</span>, <span class="country-name">Nederland</span>", …}. I currently use if (!place.geometry) to find out if the place is useful / an actual place; however I guess there's a better way ('best practice'?) to do this?


Edit 1: just stumbled across With Google Maps API V3, determine if a marker is inside a KML Layer boundary. Currently looking into it. However, I should probably note that the KML is hosted by a 3rd party and updated at will by them; as I use static site hosting I prefer not to have a separate process to extract the coordinates from polygons from the KML file. I prefer to "read" the KML (in)directly.


Edit 2: I moved from (direct) KML to a FusionTables based solution. I can now "highlight" polygons where the place is in. Now all I (still) need is a way to figure out how to show it's InfoWindow. I'll look into that tomorrow; it seems I need to query (again) into a DataTable or something and get the label info that way.


Edit 3: Solved!

How can I test unit test my jQuery-based code?

I have following code in a file named index.js. I want to test some functions in it add, print being the prime one.

(function($){
  "use strict";

  $(function(){

    var add = function(a, b){
    // ...
      },
    print = function(str){
    // ...
      },
      setup = function(){
    // ...
      },
      init = function(){
    // ...
      };

      setup();
      init();
  });
})(jQuery);

How can I do so? Does this way of coding add any security on client side? All I have is code that runs on the client side. No server involvement what-so-ever.

I tried :

var outerObj = (function(greet){
    var innerObj = (function(){
        return {test: function(){ console.log(greet); }}
    })();
    return innerObj;
})("hi");

outerObj.test();

but, in my case, innerObj line has a $ on the right hand of equal sign, making console yell error that shouts $(...) is not a function. Which I agree, it's an array of single document object.

Check out var a = (function(){ var val = $(function(){return 10;})(); })(); in any jquery enabled web-page's console, for the error.

Even if I ditch outer shell and bring $(function() {}); out. How am I gonna test that?

It's still an object, still an error.

What kind of testing can I perform, unit, bdd, etc. and how?

Ajax .post not returning data like array for JavaScript

I need a JavaScript variable like:

var test_js = {
    "first_test": "a_simple_test",
    "second_test": "other_simple_test",
    "last_test": "last_simple_test"
};

But the array is returned using ajax, i'm trying:

test.php

echo "
    'first_test': 'a_simple_test',
    'second_test': 'other_simple_test',
    'last_test': 'last_simple_test'
";

JavaScript

$.post("test.php").done(function(test_data) {
    var test_js = {
        test_data
    };
});

But when i'll minify the JavaScript (jscompress.com)

The following error is returned:

Unexpected token punc «}», expected punc «:»

How to do to fix it and return the array correctly?

Submit an input box OR a select box (not both)

I want to have the option for my users to submit a form that they have the option to either use either the select box or the input text box, but not both. Here is my form code:

    <!-- Text input-->
    <div id="incident-type" class="control-group">
      <label class="control-label" for="textinput">Incident Type (Use this box or the common incident box)</label>
      <div class="controls">
        <input id="textinput" name="incident_type" type="text" class=" form-control">
      </div>

    </div>  

<!-- Select Box -->
           <div id="incident-control-box" class="control-group">
      <label class="control-label" for="textinput">Common Incidents (Use this box or the incident type box)</label>
      <div class="controls">
        <select onclick="hideInputBox()" id="textinput incident-type1" name="incident_type" type="text" class=" form-control" >
            <option value="blank"></option>
      <option value="AFA Commercial">AFA Commercial</option>
      <option value="AFA Residential">AFA Residential</option>
      <option value="MVA W/Injuries">MVA W/Injuries</option>
      <option value="Gas Leak Outside">Gas Leak Outside</option>
      <option value="Gas Leak Inside">Gas Leak Inside</option>
      <option value="Investigation">Investigation</option>
      <option value="Possible Structure Fire">Possible Structure Fire</option>

          </select>
      </div>

    </div>

Then here is my code from my PHP where it gets the input boxes of the form:

  $incident_type     = $row['incident_type'];

The problem I run into is that I want either one of them to submit depending on what the user chooses to fill out. Currently only the select input works, not the text box input also.

How to download an image object from webgl/javascript

I have a directory with 100 images. I need a copy of them in various folders along with other information that I download from webgl. Hence I want to upload them onto the browser and download them again (hope that isn't stupid)

Here is my code:

var imagefile = model.features[cIndex].imageName.substring(model.features[cIndex].imageName.lastIndexOf('/')+1);
var image = new Image();
image.src = model.imageDirectory + imagefile;
image.onload = function() {
console.info("Read \""+image.src + "\"...Done");
}
image.onerror = function() {
var message = "Unable to open \"" + image.src + "\".";
console.error(message);
alert(message);
}

var data = image.src;

zip.file('image_RH_Original' + cIndex +'.png', data , {base64: true}); 

Is this wrong? How to I do something similar to "toDataURL" for the image object?

Javascript wont update div rails 4

Hello a rails 4 newbie here. I cant seem to get ajax to update the view. I am at a loss. I can get an alert to pop up when click the +1 link in the view but I can't get the view to update (show the votes) the span with id="ajaxed", even though the database is updating. I have read the rails guides on ajax and look at about 6 videos on youtube on how to do this and it seems right to me but doesn't work for me. here is my html:

    <tbody>
<% @topics.each do |topic| %>
  <tr>
    <td><%= topic.title %></td>
    <td><%= topic.description %></td>
    <td><span id="ajaxed"><%=pluralize(topic.votes.count, "vote")%></span></td>
    <td><%= link_to "+1",  upvote_topic_path(topic), id: "upvote", remote: true, method: :post%></td>
    <td><%= pluralize(topic.downvotes.count, "downvote") %></td>
    <td><%= link_to "-1", downvote_topic_path(topic), method: :post %></td>
    <td><%= link_to 'Show', topic %></td>
    <td><%= link_to 'Edit', edit_topic_path(topic) %></td>
    <td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

Here is my controller:

def upvote
  @topic = Topic.find(params[:id])
  @topic.votes.create
  #redirect_to topics_path
  respond_to do |format|
    format.html { redirect_to topics_path }
    format.js
  end
end

here is my upvote.js.erb:

    $('#ajaxed').text('<%=pluralize(topic.votes.count, "vote")%>');

BTW any other form of javascript or jquery that I do on the upvote.js.erb seems to work, it just wont update my '#ajaxed' span. I also tried .html and even straight js document.getElementById("ajaxed").innerHTML = '<%=pluralize(topic.votes.count, "vote")%>', this gives me unwanted results. Any help would be greatly appreciated. Thanks!!!

Can't retrieve all records from Cloudkit Cloud (JS)

I have an HTML table I want to populate with values stored in the Cloudkit Dashboard.

I have successfully retrieved records and populated my tables with them, and the problem I am noticing is that if I give it some time and try to reload the table again some records will not get retrieved. I haven't changed any of my code in the time between, so I'm very puzzled as to how/why this is happening. Below is an example of my code, and the error log:

public-query.js :

records.forEach(function(record) {  
var fields = record.fields;  
var tableActual = "<tr><td>" + record['created'].timestamp + "</td><td>" + fields['placeName'].value + </td></tr>  
                    document.write(tableActual)  

ERROR LOG:

Uncaught (in promise) TypeError: Cannot read property 'timestamp' of  undefined
at public-query.js:49:73
at Array.forEach (native)
at public-query.js:47:29

If I remove for example the <td>" + record['created'].timestamp + "</td> then the error log will say the next <td> is undefined.

To be clear, there is currently a record being retrieved WITH its timestamp correctly, and there were other records that were being retrieved and now aren't, with no change in code.

I've received this error at different times in different parts of line 3 (in the actual code there are 16 fields/<td>) even though I know that those fields are populated in the record, and have also retrieved records with those fields unpopulated.

Any idea what's going on here? Is this a bug with Cloudkit or something I am doing wrong?

is there any Yii widget "Radio Button Set "?

I'm using bootstrap in my project and I want a Radio button set like the one in following link.

<?php $radio = $this->beginWidget('zii.widgets.jui.CJuiButton', array(
'name'=>'checkbox-btn',
'buttonType'=>'buttonset',
'htmlTag'=>'span',
)); ?>
<input type="checkbox" id="check1" value="1" /><label for="check1">Checkbox 1</label>
<input type="checkbox" id="check2" value="2" /><label for="check2">Checkbox 2</label>
<input type="checkbox" id="check3" value="3" /><label for="check3">Checkbox 3</label>
<?php $this->endWidget();?>

but this doesn't seem to work, it renders like a normal radioButtonList unsure emoticon I searched in yiistrap, yiiwheels, zii and yiibooster and couldn't find a widget similar to this " radios as buttons". Should I include jquery ui for this ? I prefer using already existing widget. any suggestion ?

Typescript array map vs filter vs?

Here's a typescript method that wants to walk through an array of strings, and return another array of strings, where, strings that match the regexp (formatted something like "[la la la]" will become just "la la la" and strings that don't match are dropped. So that if my input array is:

"[x]", "x", "[y]"

it becomes

"x", "y"

Here's my code:

questions(): string[] {
    var regexp = /\[(.*)\]/;
    return this.rawRecords[0].map((value) => {
        console.log(value);
        var match = regexp.exec(value);
        if (match) {
            return match[1];
        }
    });
}

I end up with output like this:

"x", undefined, "y"

because of the "if (match)". What's the right typescript/javascript way of writing this code?

Destroy specific galleria instance among multiple galleries

I have several galleria galleries running in a web page, each in its own div. Galleria.run(#div) is used to run each gallery.

<div id="galleria" class="visible"></div>
<div id="galleria2" class="hidden"></div>
Galleria.run('#galleria',{options})
Galleria.run('#galleria2',{options})

When I collapse a gallery, I want it to be destroyed but I don't know how to retrieve the specific instance.Galleria.get() gives the list of all instances. I want something like.

gallery_array=Galleria.get();
gallery=gallery_array.find('div_id') # Find the specific instance I want to destroy
gallery.destroy();

Is there a way of doing this

Responsive Image Grid with Different Heights and Widths

I need to be able to create a responsive image grid with different image widths, (link to an image below.)

http://ift.tt/1LIWzr0

Here's what I have right now.

http://ift.tt/1RSTUd1

This ^ fits and looks good on my 27" iMac, but isn't responsive, and I haven't been able to figure out a good solution for it due to the varying heights and widths. Masonry.js didn't work for me as I'm developing this site in Wordpress and the grid is created dynamically. I need to know if there is another option for this. Thanks to all in advance!

Jquery Sometime Working fine and sometime giving "Uncaught TypeError: undefined is not a function"

Here is my script tag

Sometime It loaded all the pages, sometime few and giving the following error: Uncaught TypeError: undefined is not a function

Earlier I searched on the web about the same error, someone suggested to use jQuery.noConflict(),jQuery.noConflict(true)

I stored the value of jquery no conflict int a variable named j and replaced the jquery sign($) with j, but it didn't work. Also tried with passing a true value to no conflict as suggested by someone else on the forums, but no solution the problem.

Any help appreciated!

<script>
    //var j = jQuery.noConflict(true);
    $(document).ready(function () {
        $('#loading_status').hide();
        var total_row =946;
        var per_page = 15;
        var total_page = parseInt(total_row / per_page);

        var current_page = 0;
        var loadable = true;

        var loadNextPage = function (start, rows) {
            $('#loading_status').show();
            $.ajax({
                url: 'http://ift.tt/1dz7kgE',
                type: 'post',
                data: {
                    page: 0,
                    start: start,
                    records: rows
                },
                success: function (result) {
                    $("#flushed").append(result);
                    loadable = true;
                    $('#loading_status').hide();
                },
                error: function (xhr, status, error) {
                    alert("Error code: " + xhr.status + "\n\n\nError message: " + xhr.responseText);
                }
            });
        };

        loadNextPage(current_page, per_page);

        $(window).scroll(function () {
            if (($(window).scrollTop() + $(window).height()) >= ($(document).height() - 1000) && current_page < total_page && loadable == true) {
                loadable = false;
                current_page++;
                var start = (current_page * per_page) + 1;
                loadNextPage(start, per_page);
            }
        });

    });
</script>

How to hide html items with a radio button

This is a beginner html/css/javascript question. I've been beating my head against a wall, but still can't figure this out. I have a simple web form that users fill out(name, email, etc) and the way it's supposed to work is that when the user clicks a radio button that says "Yes" they see a drop down menu with a set number of items and when they click "No" they see a text field. I have this part working correctly, but I want the drop down menu and text field to start hidden, and then appear when the yes or no radio button is clicked. I've tried style = display:hidden; but when I used this the text and drop-down menu wouldn't appear anymore.

Thanks so much for any answers!

This is the code I'm using:

<tr align="left" valign="middle">
  <td colspan="1" rowspan="1">
    <p>&nbsp;</p>
  </td>
  <td colspan="1" rowspan="1">
    <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
  </td>
  <td colspan="1" rowspan="1">
    <p>Do you own a Zaxwerks product?</p>
  </td>
  <td colspan="1" rowspan="1">
    <p><input id="customer" name="STATUS" onclick="javascript: test();" type="radio" value="Existing Customer" /> Yes<br />
    <input id="demo" name="STATUS" onclick="javascript: test();" type="radio" value="Downloaded Demo" /> No</p>
  </td>
  <script type="text/javascript"> 
    function test() {
      if (document.getElementById('customer').checked) {
        //Show
        document.getElementById('show_customer').style.display = 'block';
        document.getElementById('show_customer2').style.display = 'block';
        document.getElementById('show_customer3').style.display = 'block';
        document.getElementById('show_customer4').style.display = 'block';

        //Hide
        document.getElementById('show_demo').style.display = 'none';
        document.getElementById('show_demo2').style.display = 'none';
        document.getElementById('show_demo3').style.display = 'none';
      } else {
        //Show
        document.getElementById('show_demo').style.display = 'block';
        document.getElementById('show_demo2').style.display = 'block';
        document.getElementById('show_demo3').style.display = 'block';

        //Hide
        document.getElementById('show_customer').style.display = 'none';
        document.getElementById('show_customer2').style.display = 'none';
        document.getElementById('show_customer3').style.display = 'none';
        document.getElementById('show_customer4').style.display = 'none';
      }
    }
  </script>
  <td>&nbsp;</td>
</tr>
<tr>
  <td colspan="1" rowspan="1" style="display: none;">
    <p>&nbsp;</p>
  </td>
  <td colspan="1" rowspan="1" style="display: none;">
    <div id="show_customer">
      <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
    </div>

    <div id="show_demo" style="display: none;">
      <p><b><font color="#cc0000" face="Georgia, Times New Roman, Times, serif" size="+2">*</font></b></p>
    </div>
  </td>
  <td colspan="1" rowspan="1" style="display: none;">
    <div id="show_customer2">
      <p>Product Owned:</p>
    </div>

    <div id="show_demo2" >
      <p>Where did you hear about us?:</p>
    </div>
  </td>
<!--This is where the user selects which product they own. (In the following code: value equals "what appears in the log file" what appears in the site menu)-->
  <td colspan="1" rowspan="1">
    <div id="show_customer3" style="display: none;">
      <p><select id="WHAT" name="WHAT" size="1">
        <option selected="selected" value="">Select One</option>
        <option value="Item 1">Item 1</option>
        <option value="Item 2">Item 2</option>
        <option value="Item 3">Item 3</option>
        <option value="Item 4">Item 4</option>
        <option value="Item 5">Item 5</option>
        <option value="Item 6">Item 6</option>
        <option value="Item 7">Item 8</option>
        <option value="Item 9">Item 9</option>
        <option value="Item 10">Item 10</option>
        <option value="Item 11">Item 11</option>
        <option value="Item 12">Item 12</option>
      </select></p>
    </div>

    <div id="show_demo3" style="display: none;">
      <p>
        <input maxlength="64" name="WHERE" size="30" type="text" value="" />
      </p>
    </div>
  </td>
  <td>&nbsp;</td>
</tr>

String split with RegExp returns empty strings at either end

// pattern -- <some name with an optional 1/2/3 at end separated by a _>
var re = new RegExp("^\(.*\)_\([1-3]\)$")
"".split(re) 
// returns [""] --- OK
"abc_d_4".split(re) 
// returns ["abc_d_4"] --- OK
"abc_d_3".split(re)
// returns ["", "abc_d", "3", ""] --- WHOA! hoped-for was ["abc_d", "3"]
// similarly, "_3".split(re), "abc_d_3_4_3".split(re)

why the extra empty strings at either end in the last case, and how to avoid that? I would definitely appreciate an explanation.

I can see similar questions have been asked before on SO but not this case (or pl point me there)

Find polygon for place in KML

NOTE: Please make sure you read my updates at the bottom!!


I have a KML file that I load 'onto' a Google Map; I also have a searchbox where users can search for a city. When the city is found I place a marker which, in most (if not all) cases should fall in one of the polygons defined in the KML.

I can click a polygon and it shows an info-popup with the areacode for that area; however: when a marker is placed I would like to have this info-popup shown automatically (and possibly other(s) that are shown before placing the marker hidden).

I have looked over the Maps V3 documentation but was unable to find anything. Is this possible?

You can view the project at http://ift.tt/1f38EtI, the source can be found at http://ift.tt/1dz7lRG

The relevant (snippet of) code is:

google.maps.event.addListener(autocomplete, 'place_changed', function () {
    var place = autocomplete.getPlace();
    if (!place.geometry)
        return;

    // Remove any existing markers
    for (var i = 0, marker; marker = markers[i]; i++)
        marker.setMap(null);
    markers = [];

    // Create a marker for place.
    var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
    });
    markers.push(marker);

    // ... Here I should figure out in which polygon the marker is positioned
    // ... and preferrably open/display the info-window which is shown when a
    // ... polygon is clicked.

    // Scroll (pan) to marker
    map.panTo(place.geometry.location);
});

Also, as a side-question: autocomplete.getPlace(); always returns an object; what is the best way to find out if the object is an actual (useful) place? When I search for xxxx for example, getPlace() returns Object {name: "xxxx"}, an actual result (like searching for Amsterdam) returns Object {address_components: Array[4], adr_address: "<span class="locality">Amsterdam</span>, <span class="country-name">Nederland</span>", …}. I currently use if (!place.geometry) to find out if the place is useful / an actual place; however I guess there's a better way ('best practice'?) to do this?


Edit 1: just stumbled across With Google Maps API V3, determine if a marker is inside a KML Layer boundary. Currently looking into it. However, I should probably note that the KML is hosted by a 3rd party and updated at will by them; as I use static site hosting I prefer not to have a separate process to extract the coordinates from polygons from the KML file. I prefer to "read" the KML (in)directly.


Edit 2: I moved from (direct) KML to a FusionTables based solution. I can now "highlight" polygons where the place is in. Now all I (still) need is a way to figure out how to show it's InfoWindow. I'll look into that tomorrow; it seems I need to query (again) into a DataTable or something and get the label info that way.


Edit 3: Solved!

How can I test unit test my jQuery-based code?

I have following code in a file named index.js. I want to test some functions in it add, print being the prime one.

(function($){
  "use strict";

  $(function(){

    var add = function(a, b){
    // ...
      },
    print = function(str){
    // ...
      },
      setup = function(){
    // ...
      },
      init = function(){
    // ...
      };

      setup();
      init();
  });
})(jQuery);

How can I do so? Does this way of coding add any security on client side? All I have is code that runs on the client side. No server involvement what-so-ever.

I tried :

var outerObj = (function(greet){
    var innerObj = (function(){
        return {test: function(){ console.log(greet); }}
    })();
    return innerObj;
})("hi");

outerObj.test();

but, in my case, innerObj line has a $ on the right hand of equal sign, making console yell error that shouts $(...) is not a function. Which I agree, it's an array of single document object.

Check out var a = (function(){ var val = $(function(){return 10;})(); })(); in any jquery enabled web-page's console, for the error.

Even if I ditch outer shell and bring $(function() {}); out. How am I gonna test that?

It's still an object, still an error.

What kind of testing can I perform, unit, bdd, etc. and how?

Ajax .post not returning data like array for JavaScript

I need a JavaScript variable like:

var test_js = {
    "first_test": "a_simple_test",
    "second_test": "other_simple_test",
    "last_test": "last_simple_test"
};

But the array is returned using ajax, i'm trying:

test.php

echo "
    'first_test': 'a_simple_test',
    'second_test': 'other_simple_test',
    'last_test': 'last_simple_test'
";

JavaScript

$.post("test.php").done(function(test_data) {
    var test_js = {
        test_data
    };
});

But when i'll minify the JavaScript (jscompress.com)

The following error is returned:

Unexpected token punc «}», expected punc «:»

How to do to fix it and return the array correctly?

Submit an input box OR a select box (not both)

I want to have the option for my users to submit a form that they have the option to either use either the select box or the input text box, but not both. Here is my form code:

    <!-- Text input-->
    <div id="incident-type" class="control-group">
      <label class="control-label" for="textinput">Incident Type (Use this box or the common incident box)</label>
      <div class="controls">
        <input id="textinput" name="incident_type" type="text" class=" form-control">
      </div>

    </div>  

<!-- Select Box -->
           <div id="incident-control-box" class="control-group">
      <label class="control-label" for="textinput">Common Incidents (Use this box or the incident type box)</label>
      <div class="controls">
        <select onclick="hideInputBox()" id="textinput incident-type1" name="incident_type" type="text" class=" form-control" >
            <option value="blank"></option>
      <option value="AFA Commercial">AFA Commercial</option>
      <option value="AFA Residential">AFA Residential</option>
      <option value="MVA W/Injuries">MVA W/Injuries</option>
      <option value="Gas Leak Outside">Gas Leak Outside</option>
      <option value="Gas Leak Inside">Gas Leak Inside</option>
      <option value="Investigation">Investigation</option>
      <option value="Possible Structure Fire">Possible Structure Fire</option>

          </select>
      </div>

    </div>

Then here is my code from my PHP where it gets the input boxes of the form:

  $incident_type     = $row['incident_type'];

The problem I run into is that I want either one of them to submit depending on what the user chooses to fill out. Currently only the select input works, not the text box input also.

How to download an image object from webgl/javascript

I have a directory with 100 images. I need a copy of them in various folders along with other information that I download from webgl. Hence I want to upload them onto the browser and download them again (hope that isn't stupid)

Here is my code:

var imagefile = model.features[cIndex].imageName.substring(model.features[cIndex].imageName.lastIndexOf('/')+1);
var image = new Image();
image.src = model.imageDirectory + imagefile;
image.onload = function() {
console.info("Read \""+image.src + "\"...Done");
}
image.onerror = function() {
var message = "Unable to open \"" + image.src + "\".";
console.error(message);
alert(message);
}

var data = image.src;

zip.file('image_RH_Original' + cIndex +'.png', data , {base64: true}); 

Is this wrong? How to I do something similar to "toDataURL" for the image object?

Javascript wont update div rails 4

Hello a rails 4 newbie here. I cant seem to get ajax to update the view. I am at a loss. I can get an alert to pop up when click the +1 link in the view but I can't get the view to update (show the votes) the span with id="ajaxed", even though the database is updating. I have read the rails guides on ajax and look at about 6 videos on youtube on how to do this and it seems right to me but doesn't work for me. here is my html:

    <tbody>
<% @topics.each do |topic| %>
  <tr>
    <td><%= topic.title %></td>
    <td><%= topic.description %></td>
    <td><span id="ajaxed"><%=pluralize(topic.votes.count, "vote")%></span></td>
    <td><%= link_to "+1",  upvote_topic_path(topic), id: "upvote", remote: true, method: :post%></td>
    <td><%= pluralize(topic.downvotes.count, "downvote") %></td>
    <td><%= link_to "-1", downvote_topic_path(topic), method: :post %></td>
    <td><%= link_to 'Show', topic %></td>
    <td><%= link_to 'Edit', edit_topic_path(topic) %></td>
    <td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

Here is my controller:

def upvote
  @topic = Topic.find(params[:id])
  @topic.votes.create
  #redirect_to topics_path
  respond_to do |format|
    format.html { redirect_to topics_path }
    format.js
  end
end

here is my upvote.js.erb:

    $('#ajaxed').text('<%=pluralize(topic.votes.count, "vote")%>');

BTW any other form of javascript or jquery that I do on the upvote.js.erb seems to work, it just wont update my '#ajaxed' span. I also tried .html and even straight js document.getElementById("ajaxed").innerHTML = '<%=pluralize(topic.votes.count, "vote")%>', this gives me unwanted results. Any help would be greatly appreciated. Thanks!!!

Can't retrieve all records from Cloudkit Cloud (JS)

I have an HTML table I want to populate with values stored in the Cloudkit Dashboard.

I have successfully retrieved records and populated my tables with them, and the problem I am noticing is that if I give it some time and try to reload the table again some records will not get retrieved. I haven't changed any of my code in the time between, so I'm very puzzled as to how/why this is happening. Below is an example of my code, and the error log:

public-query.js :

records.forEach(function(record) {  
var fields = record.fields;  
var tableActual = "<tr><td>" + record['created'].timestamp + "</td><td>" + fields['placeName'].value + </td></tr>  
                    document.write(tableActual)  

ERROR LOG:

Uncaught (in promise) TypeError: Cannot read property 'timestamp' of  undefined
at public-query.js:49:73
at Array.forEach (native)
at public-query.js:47:29

If I remove for example the <td>" + record['created'].timestamp + "</td> then the error log will say the next <td> is undefined.

To be clear, there is currently a record being retrieved WITH its timestamp correctly, and there were other records that were being retrieved and now aren't, with no change in code.

I've received this error at different times in different parts of line 3 (in the actual code there are 16 fields/<td>) even though I know that those fields are populated in the record, and have also retrieved records with those fields unpopulated.

Any idea what's going on here? Is this a bug with Cloudkit or something I am doing wrong?

is there any Yii widget "Radio Button Set "?

I'm using bootstrap in my project and I want a Radio button set like the one in following link.

<?php $radio = $this->beginWidget('zii.widgets.jui.CJuiButton', array(
'name'=>'checkbox-btn',
'buttonType'=>'buttonset',
'htmlTag'=>'span',
)); ?>
<input type="checkbox" id="check1" value="1" /><label for="check1">Checkbox 1</label>
<input type="checkbox" id="check2" value="2" /><label for="check2">Checkbox 2</label>
<input type="checkbox" id="check3" value="3" /><label for="check3">Checkbox 3</label>
<?php $this->endWidget();?>

but this doesn't seem to work, it renders like a normal radioButtonList unsure emoticon I searched in yiistrap, yiiwheels, zii and yiibooster and couldn't find a widget similar to this " radios as buttons". Should I include jquery ui for this ? I prefer using already existing widget. any suggestion ?

Typescript array map vs filter vs?

Here's a typescript method that wants to walk through an array of strings, and return another array of strings, where, strings that match the regexp (formatted something like "[la la la]" will become just "la la la" and strings that don't match are dropped. So that if my input array is:

"[x]", "x", "[y]"

it becomes

"x", "y"

Here's my code:

questions(): string[] {
    var regexp = /\[(.*)\]/;
    return this.rawRecords[0].map((value) => {
        console.log(value);
        var match = regexp.exec(value);
        if (match) {
            return match[1];
        }
    });
}

I end up with output like this:

"x", undefined, "y"

because of the "if (match)". What's the right typescript/javascript way of writing this code?

Destroy specific galleria instance among multiple galleries

I have several galleria galleries running in a web page, each in its own div. Galleria.run(#div) is used to run each gallery.

<div id="galleria" class="visible"></div>
<div id="galleria2" class="hidden"></div>
Galleria.run('#galleria',{options})
Galleria.run('#galleria2',{options})

When I collapse a gallery, I want it to be destroyed but I don't know how to retrieve the specific instance.Galleria.get() gives the list of all instances. I want something like.

gallery_array=Galleria.get();
gallery=gallery_array.find('div_id') # Find the specific instance I want to destroy
gallery.destroy();

Is there a way of doing this

Responsive Image Grid with Different Heights and Widths

I need to be able to create a responsive image grid with different image widths, (link to an image below.)

http://ift.tt/1LIWzr0

Here's what I have right now.

http://ift.tt/1RSTUd1

This ^ fits and looks good on my 27" iMac, but isn't responsive, and I haven't been able to figure out a good solution for it due to the varying heights and widths. Masonry.js didn't work for me as I'm developing this site in Wordpress and the grid is created dynamically. I need to know if there is another option for this. Thanks to all in advance!

Disabling click event of Controls in Table Data

I have a list of controls in a table data which is enclosed in a div tag as the parent tag , I want to disable the click events on my Power On and Power OFF button . Presently If I click the buttons a request is sent from my website to an IOT . I want to disable the click event on these two items .

Here is what my code looks like :

<table class="pure-table pure-table-horizontal" style="width: 90%;">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>Device Name</th>
                        <th>Status</th>
                        <th>Temperature (&#176; C)</th>
                        <th align="left">Action</th>
                    </tr>
                    </thead>

                    <tbody>

                    <% devices.forEach(function(device, i){ %>
                    <tr>
                        <td><%= (i + 1) %></td>
                        <td>
                            <%= device.name || device.macAddress %>
                        </td>
                        <td id="text_<%= device.id %>">
                            <% if (device.updateInProgress) { %>
                            <i class="fa fa-spinner fa-spin"></i>
                            <% } else if (device.powerState == false) { %>
                            <%= "Powered off" %>
                            <% } else if (device.startState == true) { %>
                            <%= "Running" %>
                            <% } else { %>
                            <%= "Not running" %>
                            <% } %>
                        </td>
                        <td>
                            <% if (device.updateInProgress){ %>
                            N/A
                            <% } else if (device.powerState) { %>
                            <div class="pure-g">
                                <div class="pure-u-1-4">
                                    <%= device.temperature %>
                                </div>

                                <!--I tried commenting this to remove temperature edit icon for single device-->

                                <!--<div class="pure-u-1-4">-->
                                    <!--<i class="fa fa-pencil-square-o" id="set_temp" data-value="<%= device.id %>"></i>-->
                                <!--</div>-->


                            </div>
                            <% } else { %>
                            N/A
                            <% } %>
                        </td>
                        <td align="left">
                            <a href='/user/startOff/<%= device.id %>?boxid=<%= id %>'
                               class="pure-button button-green <%= device.updateInProgress == true ? 'hidden' : device.powerState == false ? 'hidden' : device.startState == false ? 'hidden' : '' %>"
                               type="button">Start Off</a>

                            <a href='/user/startOn/<%= device.id %>?boxid=<%= id %>'
                               class="pure-button button-green <%= device.updateInProgress == true ? 'hidden' : device.powerState == false ? 'hidden' : device.startState == true ? 'hidden' : '' %>"
                               type="button">Start On</a>

                            <a href='/user/powerOff/<%= device.id %>?boxid=<%= id %>'
                               class="pure-button button-warning <%= device.updateInProgress == true ? 'hidden' : device.powerState == true ? '' : 'hidden' %>"
                               type="button">Power Off</a>

                            <a href="/user/powerOn/<%= device.id %>?boxid=<%= id %>"
                               class="pure-button <%= device.updateInProgress == true ? 'hidden' : device.powerState == true ? 'hidden' : '' %>"
                               type="button">Power On</a>

                            <a href="/user/deleteDevice/<%= device.id %>?boxid=<%= id %>"
                               class="pure-button button-error pull-right <%= device.updateInProgress == true ? 'hidden' : '' %>"
                               type="button ">
                                <i class="fa fa-times"></i>
                            </a>

                        </td>
                    </tr>
                    <% }) %>

                    </tbody>

                </table>

This is all running on a Node.js website .

Also ideally this is how the screen looks like with the current code :

enter image description here

I want the display to be exactly the same except the click events on "Power On" and "Power Off " should do nothing .

What I thought was to remove which I know is for making a link or a url active . But I am not able to fit the code without it .

Please help .

Displaying List from mysql data using jquery mobile

Im trying to get my squery mobile app to show certain data of mysql in a listview mode. It seems to be something wrong as nothing happens when I try it.

Here is my html:

<!DOCTYPE html> 
<html>
<head>
<meta charset="UTF-8">

<title>Watto</title>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../css/app.css" rel="stylesheet" />
<link href="../css/themes/2/watto.min.css" rel="stylesheet" />
<link href="../css/themes/2/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="../lib/jqm/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<script src="../js/listaplanesnuevos.js"></script>
<script src="../lib/jquery/jquery-2.1.4.min.js"></script>
<script src="../lib/jqm/jquery.mobile-1.4.5.js"></script>
<script src="../services/getplanes.php"></script>
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png" />
<link rel="apple-touch-icon-precomposed" href="../img/apple-touch-icon.png"/>
</head> 

<body>

<!----------PLANES NUEVOS ------------>

<div data-role="page" id="planesnuevos">

<div data-role="header" data-position="fixed">

    <h1>Planes Nuevos</h1>

    </div> <!----HEADER---->

    <div role="main" class="ui-content">


        <ul id="listaplanesnuevos" data-role="listview" data-filter="true"></ul>


    </div> <!------ CONTENT ----->

    <div data-role="footer">

        <div data-role="navbar">
            <ul>
                <li><a href="#planesnuevos" data-icon="home" class="ui-btn-active"></a></li>
                <li><a href="#search" data-icon="search"></a></li>
                <li><a href="#chooser" data-icon="eye" data-iconpos="right"></a></li>
                <li><a href="#location" data-icon="location"></a></li>
                <li><a href="../settings" data-icon="gear"></a></li>

    </div>


</div> 



</body>
</html>

Here is my JavaScript:

var serviceURL = "http://localhost/directory/app/watto/services";

var planes;

$('#planesnuevos').bind('pageinit', function(event) {
    getListaPlanes();
});

function getListaPlanes() {

    $.getJSON(serviceURL + 'getplanes.php', function(data) {
        $('#listaplanesnuevos li').remove();
        resplanes = data.items;
        $.each(resplanes, function(index, plan) {
            $('#listaplanesnuevos').append('<li><a href="detallesplan.html?id=' + plan.folio + '">' +
                'img src="pics/' + plan.foto + '"/>' +
                '<h4>' + plan.nombre + '</h4>' +
                '<p>' + plan.descripcion + '</p></a></li>');

        });
        $('#listaplanesnuevos').listview('refresh');
    });
}

and here is the PHP file

<?PHP

include 'config.php';

$sql = "SELECT `folio`, `nombre`, `descripcion`, `foto` FROM `Planes` GROUP BY `folio` ORDER BY `folio`";

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->query($sql);
    $planes = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"items":'. json_encode($planes) .'}';
} catch(PDOException $e) {
    echo '{"error":{"text":' . $e->getMessage() . '}}';
}


?>  

I don't know what is wrong, please help as im new to this.

Thanks!

How to get a different window's html with javascript

I would like to open a new window using a url, grab its html as a string and display it in the console of the original window.

From How to get element and html from window.open js function with jquery , I tried:

console.log('response', url)
    var popup = window.open(url, '_blank', 'width=500,height=500');

popup.onload = function() {
    setTimeout(function(){ console.log( 'hi',popup.document.documentElement.outerHTML) }, 2000);
}

The popup window is created, but I don't see the popup's html in the original window's console.

What am I doing wrong?

JavaScript Multiple Arrays in Object

I'm trying to display all of the items in my list below. I organized them as such in order to filter them out.

For example, I want all the titles to be separate from the array items they contain (so that the titles will display as headers and the items as regular text.

Here is my code so far:

var general = { 
    "Hardcover" : { 
        ["Book A",4],
        ["Book B",6],
        ["Book C",5]
    }
    // ... other options 
};

for (var title in general) {
   var title = ...; // assign the title variable
   $('body').append("<h2>" + title + "</h2>");
   for(var items in title) {
      // assign item variables separately 
      var itemTitle = ...;
      var itemPrice = ...;
      $('body').append(itemTitle + ": $" + itemPrice);
   }
}

So the final output would look something like:

Hardcover

Book A: $4
Book B: $6
Book C: $5

I made a quick fiddle below with my full list: http://ift.tt/1GOX7nK

changing margin-top of element while scrolling ,javascript

i want to attach an element to the bottom of a navbar the navbar is fixed so so it will be in the top when i scroll the problem is how to change the margin-top of that element so its top will be the bottom of the nav bar .. and its bottom is fixed .. (it will be hidden if i scoll a lot ) so the heigth of this element will be smaller when i scroll

here is what i did

 $(document).on('scroll', function (e) {
    $('.imagebleu').css('opacity', ($(document).scrollTop() / 500));
});

if you need more code i will post it here is the link for the page

  http://ift.tt/1LIWzqY

enter image description here

the part that contain that text is the nav bar and the other part is the .imagebleu element they have the same opacity , but because this element is under the navbar the navbar opacity doesn't look the same with it

So i want to add margin that changes by scrolling to fix this element on the bottom of the navbar

thank you very much

Accuracy Discrepancy between Google Maps and Google Geolocation API

I found a lot of treatment of geolocation accuracy, but nothing that addresses the difference between the Google API and Maps. This is on Android Chrome.

Indeed, there's a large discrepancy between the two. The API gives me 30 meters at best, but Maps manages less than 10. What gives? Here are snippets from my code:

<script type="text/javascript"
 src="http://ift.tt/1btSrES">
</script>

Then later:

function getLoc() {
 navigator.geolocation.getCurrentPosition(showLoc, errorLoc,
  {maximumAge:15000, timeout:60000, enableHighAccuracy:true});
}

function showLoc(position) {
 var elt = document.getElementById("userloc");
 elt.innerHTML = "Lat " + position.coords.latitude + "&nbsp;&nbsp;" +
                 "Long " + position.coords.longitude + "&nbsp;&nbsp;" +
                 "Accuracy " + position.coords.accuracy;
}

function errorLoc(msg) {
 alert(msg);
}

Deferring google charts

I have this google charts code which works fine:

<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript" async>

google.load("visualization", "1", {packages:["corechart"]});

var t1 = 'IndexTitle'
var t2 = 'IndicatorTitle'

google.setOnLoadCallback(function(){drawChart1(t1)});
google.setOnLoadCallback(function(){drawChart2(t2)});

function drawChart1(t){
var data = new google.visualization.DataTable();
data.addColumn('string','Date');
data.addColumn('number','Close');
data.addColumn({type: 'string', role: 'tooltip'});
data.addRows([ChartIndexData...........]);
var options = {
    title: t,
    colors:['black'],  
    legend: {position: 'none'},
    chartArea:{left:60,top:20,width:'90%',height:'90%'}
   };
var chart = new google.visualization.LineChart(document.getElementById('chart1_div'));
chart.draw(data, options);
}

function drawChart2(t){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', '');
data.addColumn({type: 'string', role: 'tooltip'});
data.addRows([ChartIndicatorData...................]);
var options = {
    title: t,
    legend: {position: 'none'},
    chartArea:{left:60,top:20,width:'90%',height:'60%'}
  };
var chart = new google.visualization.LineChart(document.getElementById('chart2_div'));
chart.draw(data, options);
}<%
</script>

The problem is when I test the page on Google PageSpeed insite the score is 49/100 because of the script above:

Remove render-blocking 
JavaScript:http://ift.tt/JuZcy0
http://ift.tt/1GOX7nA
http://ift.tt/1HwfAdf

Optimize CSS Delivery of the following:
http://ift.tt/1GOX634
http://ift.tt/1HwfylR

As I understand I have to load javascript Asynchronous or defer the loading.

How do I fix it.

jssor onclick open larger version

Is it possible using jssor to click on a photo in the slideshow and on click make it open a larger photo (responsive/mobile-friendly), e.g. in a popup?

Currently I'm using the following code:

<script>
        jQuery(document).ready(function ($) {
        var _SlideshowTransitions = [{ $Duration: 500, $Opacity: 2, $Brother: { $Duration: 1000, $Opacity: 2 } }];

        var options = {
                $FillMode: 1,
                $DragOrientation: 3,
                $AutoPlay: true,
                $AutoPlayInterval: 5000,
                $SlideshowOptions: {
                        $Class: $JssorSlideshowRunner$,
                        $Transitions: _SlideshowTransitions,
                        $TransitionsOrder: 1,
                        $ShowLink: true
                }
        };

        var jssor_slider1 = new $JssorSlider$('artikelphoto', options);
});
</script>
<div u="slides" style="position: absolute; overflow: hidden; left: 0px; top: 0px; width: 200px; height: 200px;">
  <div><img u="image" src="/1.jpg" /></div>
  <div><img u="image" src="/2.jpg" /></div>
</div>

How do I make this code refresh every minute?

How do I make this code refresh every minute?

<script type="text/javascript">
$j(document).ready(function () { 
    $j('#left-box').load('pages/box.php'); 
});
</script>

I want it to refresh every 1 minute I've tried other stuff cant do it

ajax queries still waiting after window close

I have webpage that has an ajax call that gets data from a php script.

ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", "submit.php?id=" + id, true);
ajaxRequest.send(null);

Inside the submit.php I wait for a binary to finish and create an outfile.

while(1){
    if(is_file($OUTFILEPATH)){
        break;
    }else{
        sleep(60);
    }
}

The problem is that if the user closes the browser window, the ajax call and corresponding httpd are not aborted.

And if the user refreshes the webpage multiple times, I end up having hundreds of httpd processes all waiting for the the same outfile to be created.

Apache Server Status
115 requests currently being processed, 5 idle workers

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW_W____........
................................................................
................................................................

Scoreboard Key:
"_" Waiting for Connection, "S" Starting up, "R" Reading Request,
"W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,

minimum set of module/methonds in jquery code for selector

I am reading jquery code now. I found the following methods are suitable for cross platform programming. (desktop, web browser and mobile app)

$(selector)
$.ajax()     <----------I am not sure if this is veryuseful
$(selector).find()
$(selector).bind()
$(selector).unbind()
$(selector).delegate()
$(selector).remove()
$(selector).attr()
$(selector).html()<-----I am not sure if this is veryuseful

I mean that I prefer the javascript native code to process logic bussiness except some selector/dom function. This means that I even can use the same logic code in QT/QML.

Is there is minimum set of module/methonds for the methods above?

Your comment welcome

minimum set of module/methonds in jquery code for selector

I am reading jquery code now. I found the following methods are suitable for cross platform programming. (desktop, web browser and mobile app)

$(selector)
$.ajax()     <----------I am not sure if this is veryuseful
$(selector).find()
$(selector).bind()
$(selector).unbind()
$(selector).delegate()
$(selector).remove()
$(selector).attr()
$(selector).html()<-----I am not sure if this is veryuseful

I mean that I prefer the javascript native code to process logic bussiness except some selector/dom function. This means that I even can use the same logic code in QT/QML.

Is there is minimum set of module/methonds for the methods above?

Your comment welcome

AngularJS localstorage for a factory

I am a newbie to IonicFrameWork and was following their "starter tab" template and made a few modifications to "delete" and "bookmark" items from a factory.

My books.js which contains the factory looks as follow:

.factory('Books', function() {

  // books data
  var books = [{
    id: 0,
    title: 'Sample Title',
    author: 'Sample Author',
    category: 'Horor, Fiction',
    cover: '/cover.jpeg',
    details: 'some details about the book',
    chapters: [
      {
        id : 1,
        name: 'Chapter 1',
        filename: 'chapter1.html',
      },
      {
        id : 2,
        name: 'Chapter 2',
        filename: 'Chapter2.html',
      }
    ]
  }
  .....  
  return {
    all: function() {
      return books;
    },
    // remove a book from the list
    remove: function(book) {
      books.splice(books.indexOf(book), 1);
    },

and my controllers.js looks like this:

....
.controller('DashCtrl', function($scope, Books) {

  $scope.books = Books.all();
  $scope.remove = function(book) {
    Books.remove(book);
  };
})
.controller('singlebookCtrl', function($scope, $stateParams, Books){
  $scope.book = Books.get($stateParams.bookId);
  $scope.toggleIcon = function ($evemt, iconName, book){
  var buttonClasses = $event.currentTarget.className;
  // add the book to favorite
  if (....){
      book.isFavorite = true;
  }
  // remove the book from favorite 
  else {
      book.isFavorite = false;
  }
  ....

when I exit the app and open it again, the deleted item is back and favorite items are gone.

When searching for a solution , I came across this article which states I should use window.localstorage. But not sure how I should apply this method for a factory.