...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 3, 2012

Is there an inbuilt way to use JQuery's .each() in reverse?

Question by Marty Wallace

Possible Duplicate:
JQuery .each() backwards

What is the easiest way to use .each() in reverse? At the moment I am doing this:

var temp = [];

$("#nav a").each(function()
{
    temp.push($(this));
});

temp.reverse();
for(var i = 0; i < temp.length; i++)
{
    var a = temp[i];

    // Work with a.
}

It would be nice if I could do something like:

$("#nav a").reverse().each(function()
{
    // Work with $(this).

});

The context is that I have a collection of elements using float: right which displays them in reverse order and I want to iterate over them from left to right like normal.

Answer by Starx

Use this

$($("#nav a").get().reverse()).each(function() { 
     //..........
});
Read more

How can I have the user change options of the jQuery UI Slider?

Question by Sam Pellino

I have a jQuery UI slider on my page. It starts out with:

$( "#slider" ).slider({
    value: 6,
    min: 6,
    max: 120,
    step: 6
});

Which works fine.

I have a select element next to it with 6, 12, and 24 as options.
What I would like to accomplish is for the user to select 12, and the slider’s step, min, and value all go to 12 (same for 24). I have already tried to build a function:

$('#dropdown').change(function(){
    $( "#slider" ).slider( "option", "value", $(this).val() );
    $( "#slider" ).slider( "option", "min", $(this).val() );
    $( "#slider" ).slider( "option", "step", $(this).val() );
    $( "#slider" ).slider( "option", "max", 120 );
});

However all this does is make is go to value 12, then upon clicking the slider, it jumps all the way to the end (120) and just stays there.

Do I need to destroy the slider and make it again from scratch?

EDIT #1:

I did just download Firebug and check the slider with the console, and the values are all returning correct (min=12,value=12,step=12,max=120). Does anyone know why it’s being so stubborn and jumping/sticking to the end?

Answer by DigitalBiscuits

Found the issue.
You need to parse the value from the <select> to an int before you use it to change the options of the slider.

$('#dropdown').change(function()
{
    var currentVal =  parseInt($("#slider").slider("value"));
    var newOptions = parseInt($(this).val());
    $( "#slider" ).slider( "value", currentVal);
    $( "#slider" ).slider( "option", "min", newOptions );
    $( "#slider" ).slider( "option", "step", newOptions );
    $( "#slider" ).slider( "option", "max", 120 );
});

Working Example

http://jsfiddle.net/DigitalBiscuits/VSBCT/1/

Answer by Starx

Implementation is correct. But you can cache the results

$('#dropdown').change(function(){
    var val = this.value;
    $( "#slider" ).slider( "option", "value", val );
    $( "#slider" ).slider( "option", "min", val );
    $( "#slider" ).slider( "option", "step", val );
    $( "#slider" ).slidYou can er( "option", "max", 120 );
});
Read more

Closing HTML Tags Automatically

Question by user870283

I’ve allowed users to use <pre></pre> tags to display code in comments and articles, but I’ve come across a problem that I’m struggling to solve. When a user fails to close an HTML tag, for example:

    <pre>
        <html>
            <head>

            </head>
    </pre>

the comment appears to be blank. What I’m looking for is some sort of function that will automatically close any HTML tags that the user missed.

Thanks in advance.

Answer by cha55son

Well it’s going to get nasty if you dont use a framework but your courage is admired. Hopefully this will be a nudge in the right direction.

The simplest, non-framework solution I can think of is using a stack to push and pop tags while parsing the string from the user.

pseudo code

userData = getUserData();
stack = array();
loop (line in userData) {
   matches = search for "<*>"; // may have multiple on one line
   loop (match in matches) {
      tagName = getTagNameFrom(match);
      if ("/" is not found) {
         push tagName on stack;
      } else if ("/" is found) {
         pop tagName off stack; 
         // There was an error if the stack is
         // empty or the tagName that was popped was not
         // the same.
      }
   }
}

This is by no means comprehensive and a framework is really recommended here, but hopefully it can help out a bit.

Answer by Starx

You can use HTML Tidy to solve this problem. To finds and closes the unclosed tags, automatically.

Project Page

Read more

Changing .css in jQuery using static values

Question by jsuissa

I used the PHP below using regex to resize the font-size/line-height of an html page.
I’d like to create similar fucntionality in jQuery.

Is there a way to store static values for an entire method like .css() so each time the scale calculations are based off the original value instead of their current value?

jQuery code excerpt:

$("#resume_holder").contents().find('body').children().css('font-size', '+=' + ui.value);

PHP Code:

private function _font_size($output,$scale,$line_height_scale =  FALSE) {

        $callback = new Font_Callback($scale);
        $pattern = '%(bfont-size:s*)([0-9]+)%s';
        $output  = preg_replace_callback($pattern, array($callback, '_alter_font_size'), $output);  

        if ($line_height_scale === FALSE) {
        $callback = new Font_Callback($scale);
        } else { $callback = new Font_Callback($line_height_scale); }
        $pattern = '%(bline-height:s*)([0-9]+)%s';
        $output  = preg_replace_callback($pattern, array($callback, '_alter_font_size'), $output);  
        return($output);
}

Answer by Starx

You can use jQuery’s .data() for that.

$("img").data("yourvar", "yourvalue");
Read more

Having trouble passing text from MySQL to a Javascript function using PHP

Question by Nate

So here’s the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.

At some point I want to pass this data into a javascript function called foo.

// This is a PHP block of code
// $someText is text retrieved from the database

echo "<img src=someimage.gif onclick="foo('{$someText}')">";

If the data in $someText has line breaks in it like:

Line 1
Line 2
Line 3

The javascript breaks because the html output is

<img src=someimage.gif onclick="foo('line1
line2
line3')">

So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?

===========================================================================================

After using json like this:

echo "<img src=someimage.gif onclick="foo($newData)">";

It is outputting HTML like this:

onclick="foo("line 1<br />rnline 2");">

Which displays the image followed by rnline 2″);”>

Answer by Cal

json_encode() is the way to go:

$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick="foo($safe)">";

You can see a demo here: http://codepad.org/TK45YErZ

Answer by Starx

Only json_encode() is enough to escape the new line

echo "<img src=someimage.gif onclick="foo(".json_encode($newData).")">";
Read more

How can I echo a COUNT query

Question by Tom Gillespie

I’m new to mySQL and as such am just looking for a very simple COUNT query which I haven’t found explained online with any real clarity.

What I’m looking to do is

COUNT the number of rows in my PASSENGER table where groupID = 0, and then be able to echo the numerical value that the count will return, how can I do this?

Answer by Starx

Something like this

$query = "SELECT COUNT(*) c FROM PASSENGER WHERE groupID = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($query);
echo $row['c']; //Here is your count
Read more

Ajax return var with server response

Question by Tomirammstein

I have this function, just make a simple request to the server, simply AJAX.

( function() {
'use strict';
Request  = { 
    Call: function ( u, theme, params ) { 
      var ajax, t; ajax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 
      ajax.onreadystatechange = function() { 
        if ( ajax.readyState == 4 ) { 
          this.Reponse = ajax.responseText; 
        } 
      }; 
      if ( theme == 'POST' ) { 
        ajax.open('POST', u, true); 
        ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 
        ajax.send(params); 
      } 
      else { 
        if ( theme == 'GET' ) { 
          ajax.open('GET', u, true); 
          ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
          ajax.send(null); 
        }  
      } 
    },
    Response : null
  } 
})();

I want to store the server’s response into a variable, like this :

window.onLoad = function () {
  Request.call('post.php', 'POST', 'bar=foo');
  //then
  document.getElementById('foo').innerHTML = Ajax.Request.Response;
}

Because I want to process the response separately.

Somebody can help me?

Answer by Starx

You can access the response using responseText

var response = ajax.responseText
Read more

Can AJAX or PHP "echo" too much?

Question by Marc Brown

This a question that is more on the lines of server efficiency and availability.

Say I have a php page that calls a AJAX script and 1 million users are connecting within the same second.

Would there be a performance boost if I limit the AJAX script so that it only echos once instead of every time it receives data?

I planned on printing all the data to a variable and then echoing that variable once the script is finished.

I’m not sure if echoing is simply storing the data in the server until the script finishes, similar to what I want to do above or if it is actually connecting with the client each time?

If a connection is made for each echo then that would be better than filling a variable with data, possibly causing the RAM to fill up fast?

This AJAX script is pulling data from a database (calls PHP page). I have a lot of “echo” statements that are simply printing table, div, tr, etc tags and then finally the data from the database. Then, once again printing table, div, tr, etc tags. Your saying that it’s better to simply fill a variable with this data and print/echo ONCE?

Thanks,

Answer by Starx

Generally, servers processes scripts and sends the output in the form of HTML, so there is no longer link between a page and server. When you are making a AJAX request, you will open the connection again and send the request.

The main bottleneck in the performance occurs from the amount of request you send to the server. You should limit the request as much as possible.

If a connection is made for each echo then that would be better than filling a variable with data, possibly causing the RAM to fill up fast.

You are wrong about this, You should minimize the request as much as possible, especially, when you are processing a large number of people.


Next, Its nearly pointless to update the content onevery pass. Look how facebook updates its content. The timers and contents are updated every minute. Except the notification part.

Read more

css absolute position won't work with margin-left:auto margin-right: auto

Question by user1118019

Say you have the following css applied to a div tag

.divtagABS {
    position: absolute;
    margin-left: auto;  
    margin-right:auto;
 }

the margin-left and margin-right does not take effect

but if you have relative, it works fine
i.e.

,divtagREL {
position: relative;
margin-left: auto;  
 margin-right:auto;
}

why is that? i just want to center an element

can someone explain why setting margins to auto in absolute position does not work?

Answer by kmb385

An element with position absolute has been removed from its normal place within the DOM. It cannot be centered because it does not have an actual parent to calculate the margins and be centered within.

Position relative works because the element has a parent which can be used to calculate the margins.

This article gives a good overview of assigning margins to absolutely positioned elements: http://www.vision.to/articles/margins-and-absolute-positioning.php

This forum provides a good description of why it does not work:
http://www.justskins.com/forums/css-margins-and-absolute-82168.html

Answer by Starx

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }
Read more

if/else statement in a function: using onclick as a switch

Question by Aurora Schmidt

I have looked for solutions to this on google for what seems like an eternity, but I can’t seem to formulate my search correctly, or nobody has posted the code I’m looking for earlier.

I am currently trying to make a function that will modify one or several margins of a div element. I want to use an if/else statement within the function, so that the onclick event will switch between the two conditions. This is what I have been working on so far;

function facebookToggle()
{
    if($('#facebooktab').style.margin-left == "-250px";)
    {
        document.getElementById("facebooktab").style.marginLeft="0px";
    }
    else
    {
        document.getElementById("facebooktab").style.marginLeft="-250px";
    }
}

I have tried twisting it around a little, like switching between “marginLeft” and “margin-left”, to see if I was just using the wrong terms.. I’m starting to wonder if it might not be possible to combine jQuery and regular javascript? I don’t know.. It’s all just guesses on my part at this point.

Anyway, I have a div, which is now positioned (fixed) so almost all of it is hidden outside the borders of the browser. I want the margin to change onclick so that it will be fully shown on the page. And when it is shown, I want to be able to hide it again by clicking it.

I might be approaching this in the wrong way, but I really hope someone can help me out, or even tell me another way to get the same results. Thank you for any help you can give me.

You can see it in action at: http://www.torucon.no/test/

(EDIT: By the way, I am a complete javascript novice, I have no experience with javascript prior to this experiment. Please don’t be too harsh, as I am aware I probably made some really stupid mistakes in this short code.)

Fixed problem:

function facebookToggle() {
var fb = $('#facebooktab'); // save reference to element
if( fb.css('margin-left') === '-250px' ) {
    fb.css('margin-left', '0px');
} else {
    fb.css('margin-left', '-250px');
}
}

Answer by paislee

A jQuery object doesn’t have a property called style, so

if($('#facebooktab').style.margin-left == "-250px";)
//                   also remove this semi-colon! ^

is going to throw an error. Some options for accessing CSS properties are (1)

document.getElementById("facebooktab").style.marginLeft;

which you have correctly used, or (2)

$('#facebooktab').css('margin-left');

Consider being consistent and using the same approach for all three cases. You can assign css properties with jQuery like

$('#facebooktab').css('margin-left', '-250px');

With these things in mind, here’s a suggested rewrite:

function facebookToggle() {
    var fb = $('#facebooktab'); // save reference to element
    if( fb.css('margin-left') === '-250px' ) {
        fb.css('margin-left', '0px');
    } else {
        fb.css('margin-left', '-250px');
    }
}

and here’s another that uses a predefined CSS class:

#facebooktab {
    margin-left: -250px; /** default state */
}

.no-left-margin {
    margin-left: 0px;
}
function facebookToggle() {
    $('#facebooktab').toggleClass('no-left-margin');
}

Answer by Starx

Since you are mixing jQuery with javascript, you got mixed up. Apart from what paislee’s advice. you are do this too.

if($('#facebooktab')[0].style.margin-left == "-250px";){
    document.getElementById("facebooktab").style.marginLeft="0px";
}
else    {
    var fb = document.getElementById("facebooktab");
    fb.style.marginLeft="-250px";
}
Read more
...

Please fill the form - I will response as fast as I can!