...

Hi! I’m Starx

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

Trying to incrementally animate "marginTop" with jQuery, but it resets each time. Why?

Question by K.K. Smith

I’m having trouble implementing a “scroll more text” feature.

<a href="#" id="scroll-trigger">More</a>

<div id="outer-frame">
<div id="scroll-frame">

.. long text

</div>
</div>

.. in the css

#outer-frame {
height:200px;
overflow:hidden;
}

and the Jquery ..

$(document).on("click","#scroll-control",function(e){
    (e)preventDefault();
    $('.scroll-frame').animate({"marginTop":"-=50px"},1000);     
});

That’s the basic construction. There is more to it, but even when I have stripped down to this it does not work like I would expect.

I simply want the user to be able to scroll the text up by 50px increments.

But each time the #scroll-trigger is clicked, the .scroll-frame “resets” and scrolls from 0 up to -50px.

I have tried grabbing the dynamic CSS each time

$(document).on("click","#scroll-control",function(e){
    (e)preventDefault();
    var newMarginTop = ($('.scroll-frame').css('marginTop'));  // should get the new value?
    newMarginTop -= 50;
    $('.scroll-frame').animate({"marginTop": newMarginTop },1000);     
});

That didn’t work either. It still resets and scrolls from zero. What am I not getting? I’m looking at the jQuery manual and this ..

$("#left").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});

.. moves the box progressively more and more to the left. Why is my situation different?

Answer by Starx

  1. Your animate() property is invalid

    • animate({"marginTop":"-=50px"}
    • animate({"left": "-=50px"}

    Remove the = sign from these

    In case you are trying to set the new values 50px less, you can try something like this.

    animate({"marginTOp" : $(this).css("marginTop")-50 });
    
  2. You are using the event object on the wrong way

    (e)preventDefault();
    

    Change this to e.preventDefault();

Read more

Jquery click event is not fired every time on all LI element of UL tag

Question by Rama Rao M

Hi,

I have created drop down.A div tag contains ul which has list items.Whenever user clicks on the li element,that value has to be updated in the input box.The problem is click event is not fired on some of li elements.In first case, I put 3 LI elements,out of these only top two elements firing event but no last one.In second case, I changed LI elements to 5.Now only first 3 elements firing but not last 2.
Out f 8 elements 5 elements firing,but not last 3 elements. I am really confused with this behavior. What could be the wrong in my code..Here is the link .Can you please help me….

Answer by codef0rmer

The following line in your code causing a problem: (I do not think it is needed as you have $(html).click() event too)

$('.irmNDrdnInput').blur(function(){
    drndValId = 'drdn-val-'+$(this).attr('id').split('-')[2];
    $('#'+drdnValId).slideUp(300);
});

Demo: http://jsfiddle.net/6Kd67/5/

For tab-press, you can track the keyCode inside $('.irmNDrdnInput').keydown() event :

if (event.keyCode === 9) {
    $('.irmNDrdnVal').slideUp(300);
    return false;            
}

Demo: http://jsfiddle.net/6Kd67/7/

Answer by Starx

Why are over complicating this effect? Keep it Short and Simple (KISS)

I created a simple demo for a previously asked question, check it here.

Another demo with slide in effect.


Update

Your blur function is creating problem, since more than one event is being triggered at the same time, specially the $('html').click(), the effect is overlapping. Add a slight delay to get everything working

/*Close value popup of the element which has lost focus*/
$('.irmNDrdnInput').blur(function(){
    drndValId = 'drdn-val-'+$(this).attr('id').split('-')[2];
    $('#'+drdnValId).delay(100).slideUp(300);
});

Working DEMO

Read more

How can I use getimagesize() with $_FILES['']?

Question by eric01

I am doing an image upload handler and I would like it to detect the dimensions of the image that’s been uploaded by the user.

So I start with:

if (isset($_FILES['image'])) etc....

and I have

list($width, $height) = getimagesize(...);

How am i supposed to use them together?

Thanks a lot

Answer by Starx

You can do this as such

$filename = $_FILES['image']['tmp_name'];
$size = getimagesize($filename);

// or

list($width, $height) = getimagesize($filename);
// USAGE:  echo $width; echo $height;

Using the condition combined, here is an example

if (isset($_FILES['image'])) {
    $filename = $_FILES['image']['tmp_name'];
    list($width, $height) = getimagesize($filename);
    echo $width; 
    echo $height;    
}
Read more

css form- input/textarea styling & positioning.. code & image included

Question by AMC

I’m new to web design, so please forgive if this is super simple- I’ve tried everything I know and can’t quite seem to get this right.

I’ve put together a contact form using html & css. Ideally, I’d like to have a 1px line extending from each label to use as an input guide. This line should be level with the bottom of the label. I’d also like a series of lines extending vertically in the text area to allow for extra writing space.

Currently, the input lines for Name and Email aren’t showing, and there is only one line at the very bottom of the textarea for Message.

Here’s the code I’m working with:

    <div id="contact-form">
        <div id="invite">
            <h1>Let's Talk.</h1>
            <div class="postinfo">
                <h2>Have you got a project needing an eye for detail and a creative touch? I'd love to hear from you.</h2>
            </div><!-- end postinfo -->
        </div><!-- end invite -->
        <form>

            <label for="user">Name:</label>
            <input type="text" name="user" value="" /><br />

            <label for="emailaddress">Email:</label>
            <input type="text" name="emailaddress" value="" /><br />

            <label for="comments">Message:</label>
            <textarea name="comments"></textarea><br />

            <input type="submit" name="submitbutton" id="submitbutton" value="Submit" />
        </form>
    </div><!-- end contact -->

#contact-form {
    float: left;
    margin-left: 300px;
    margin-top: 310px;
}

#invite .postinfo {
    list-style-type: none;
    width: 150px;
}

label {
    float: left;
    font-family: dalle;
    font-size: 160%;
    letter-spacing: 2px;
    text-transform: uppercase;
    margin-left: 200px;
    margin-top: -105px;
    width: 120px;
}

input, textarea {
    border-style: none;
    border-bottom: 1px solid #202020;
    margin-bottom: 5px;
    margin-left: 300px;
    margin-top: -105px;
    width: 245px;
}

textarea {
    width: 250px;
    height: 150px;
}

#submitbutton {
    background: none;
    border-style: none;
    font-family: Georgia, 
                 Constantia,
                 "Lucida Bright",
                 "Bitstream Vera Serif",
                 "Liberation Serif",
                 serif;
    margin-left: 173px;
    margin-top: 5px;
    width: 90px;
}

br {
    clear: left;
}

Ideal outcome:

ideal outcome

Answer by Starx

There were some unneeded CSS rules on your codes. Try this demo to see it fixed to some extent but lines on text area cannot be achieved using CSS.

You need to use image for that. See a demo

Read more
March 20, 2012

Positioning a jQuery UI dialog offset from the Center

Question by Hawkee

I’d like to position my jQuery UI dialogs a bit better. The default “center” position puts them directly in the middle of the page, but it certainly looks better to have them offset about 70% up the page as they are in Facebook. I’m looking at the .position function but am a bit unclear what the simplest solution is.

Answer by Starx

The easiest way would be to use the position()

$("#dialog").dialog("widget").position({
       my: 'left',
       at: 'right',
       of: target
});

Or, if you already have calculated the dimensions

var x = 50; //calculate the 70%, with your own logic
var y = 100;
$("#dialog").dialog('option', 'position', [x,y]);

Or you can specify the height during initialisation of the widget

$("#dialgo").dialog({
     autoOpen: false, 
     width: 400 , 
     position: [300,200] 
});
Read more

Can I use jquery Mobile with HTML 4.01?

Question by pcharb

Can I use jQuery mobile library with HTML 4.01 transitional or do I have to use HTML5 to use it?

Answer by Starx

Yes, you can use both with jQuery Mobile. Just choose the one appropriate on your case.

For that you might need to know some of the differences among mobile technology regarding web and versions of different html.

I suggest reading these articles.

  1. HTML 4/5 Mobile Applications
  2. HTML 5 in mobile devices
  3. HTML 4.0 Guidelines for Mobile Access
Read more

PHP Echo and Includes

Question by Kevin Schueller

When I use the following PHP code:

$id = $_GET['page']; $page = include ($id.'.php'); echo $page;

The code within the $id.php file is returned, however there is a “1” appended to it, any idea why this is happening?

Answer by Marc B

include() will return boolean TRUE if the file was successfully included. You then echo out that true value, which is printed as a 1.

Of note: never directly use user-provided data ($_GET[‘page’]) in file system operations. It’s a hideious security risk. You’ve at least got .php being appended so it’s not quite as large a gaping hole, but still… don’t do this.

Answer by Starx

  • You shouldn’t echo a page like that.

    include() is used to import the document onto your current working file.

  • By using $page = include ($id.'.php');, you are assigning boolean value to $page

    This will hold the success status of the include() statement

    • If the page load successfully, it give true, whose numeric value is 1
    • If the load was unsuccessfully, it gives false, whose numeric value is 0

However, the way you are using is not entirely incorrect

For example: Create a page Test.php to return a value at the end

$t = “some text”;
return $t;

Then you will able to use it to echo

echo include("test.php"); //outputs "some text"

I suggest you tead the documenation for complete guide

Read more

Determining duplicate letter counts between an array of strings

Question by kavisiegel

I have an array of strings of random letters, and I need to know which letters are consistent between the array members. The count of the letters are important.

My method right now is loop through the array, doing a split, then looping through the spitted string to count the occurrences of each letter, then update the array with letter => count

Then do an array_reduce that creates a new array of members who only occur in all arrays. But, it’s not working.

<?
$a[] = "emaijuqqrauw";
$a[] = "aaeggimqruuz";
$a[] = "aabimqrtuuzw";
$a[] = "aacikmqruuxz";
$a[] = "aacikmqruuxz";
$a[] = "aaciimqruuxy";

foreach($a as $b){
    $n = str_split($b, 1);
    foreach($n as $z){
        $arr[$z] = substr_count($b, $z);
    }
    ksort($arr);
    $array[] = $arr;
    unset($arr);
}

$n = array_reduce($array, function($result, $item){
    if($result === null){
        return $item;
    }else{
        foreach($item as $key => $val){
            if(isset($result[$key])){
                $new[$key] = $val;
            }
        }
        return $new;
    }
});

foreach($n as $key => $val){
    echo str_repeat($key, $val);
}

This returns aaiimqruu – which is kinda right, but there’s only 2 i‘s in the last element of the array. There’s only one i in the rest. I’m not sure how to break that down farther and get it to return aaimqruu– which I’ll then pop into a SQL query to find a matching word, aquarium

Answer by kavisiegel

Seems like array_reduce is the best function for what this purpose, however I just didn’t think of adding a conditional to give me the desired effect.

$new[$key] = ($result[$key] > $val) ? $val : $result[$key];

to replace

$new[$key] = $val;

did the trick.

Answer by Starx

How about you do it this way? Finds out the occurrence of an item throughout the array.

function findDuplicate($string, $array) {
   $count = 0;
   foreach($array as $item) {
        $pieces = str_split($item);
        $pcount= array_count_values($pieces);
        if(isset($pcount[$string])) {
           $count += $pcount[$string];
        }
   }
   return $count;
}

echo findDuplicate("a",$a);

Tested 🙂

Gives 12, using your array, which is correct.


Update

My solution above already had your answer

    $pieces = str_split($item);
    $pcount= array_count_values($pieces);
    //$pcount contains, every count like [a] => 2
Read more

How to increment number in string using Javascript or Jquery

Question by user983208

The id of my textarea is string and of this format

id=’fisher[27].man’

I would like to clone the textarea and increment the number and get the id as fisher[28].man and prepend this to the existing textarea.

Is there a way to get this done easily with jquery?

var existingId = $("#at textarea:last").attr('id');
var newCloned = lastTextArea.clone();
var newId = newCloned.attr('id');
//add the index number after spliting
//prepend the new one to 
newCloned.prepend("<tr><td>" + newCloned + "</td></tr>");

There has to be easier way to clone, get index number, split and prepend.

I’m have also tried to do this with regEx

var existingIdNumber = parseInt(/fisher[(d+)]/.exec(s)[1], 10);

Can anybody help me with this?

Answer by Starx

Correct regex would be this

/fisher[d+].man/

Here is a way through through which you would extract the the id.

id = text.replace(/fisher[(d+)].man+/g,"$1");
//Now do whatever you want with the id

Similarly, Same replacement technique can be used to get an incremented id as:

existingId = 'fisher[27].man';
newId = existingId .replace(/(d+)+/g, function(match, number) {
       return parseInt(number)+1;
});
console.log(newId);

Demo with both usage

Read more

multiple "HTML" tags in HTML file: how to separate CSS rules when classes and id's can be the same?

Question by P5music

I see that multiple HTML tag file is correctly rendered by the browser. I mean like two html files merged and concatenated. But if I put a STYLE region into each of the HTML parts and the classes or id’s are the same I get the last css rules applied also to the first part. I ask how to make css rules acting just on the part they are inserted, even the classes and ids are the same. I need this special thing, so I am looking for a solution or a trick.

Answer by stefan bachert

I think multiple html-Tags in one document are not allowed.
I do not see any advantages for doing so.

When you have multiple documents, consider to use the frame or better iframe-tag

Answer by Starx

Having multiple elements with same id is very error prone. Breaks on more than one occasion like

On javascript: document.getElementById('idname');

Read more
...

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