...

Hi! I’m Starx

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

Select recursive :last-child. Possible?

Question by Lasse Dahl Ebert

In CSS, is it possible to recursively select all :last-child from body?

Given this markup:

<body>
  <div id="_1">
    <div id="_2"></div>
  </div>
  <div id="_3">
    <div id="_4">
      <div id="_5"></div>
      <div id="_6"></div>
    </div>
  </div>
</body>

I am looking for div no. 3, 4 and 6

Another way to put it is this:

body > :last-child,
body > :last-child > :last-child,
body > :last-child > :last-child > :last-child,
body > :last-child > :last-child > :last-child > :last-child {
  /* My stuff here */
}

But obviously this is not a good approach.

Answer by BoltClock

No, unfortunately that’s just about the only way to do it without modifying the HTML.

There has been at least one request for recursive versions of the :first-child and :last-child pseudo-classes, but it doesn’t seem to have gained much favor. Notice it suggests nesting and repeating the pseudo-classes in the same way as in your question:

Currently, AFAIK, we can only match children up to some exact nesting level known in advance (3 in the example below):

.container > :first-child,
.container > :first-child > :first-child,
.container > :first-child > :first-child > :first-child {}

We cannot use just :first-child context selector since it would also select first children of blocks that are not first children themselves.

So we need a sort of recursive selector that matches not just first of last child, but recursively matches all first-most and last-most elements regardless of their nesting level.

Answer by Starx

No need to chain all the way. It would be simply like this

div:last-child {
   /* Your GREAT css */
}

Demo

Update: On that case, give the div2 a typical class and use :not() to push out of the selection

div:last-child:not(.nolist) {
    border: 1px solid red;
}

Demo

Read more

Prevent multiple selection of a div

Question by user1551056

I have multiple divs on my page.I want to copy selected text from div1 to div2 only.Selection on div2, div3, div4 should not get copied. If ctrl+A is pressed or multiple divs are selected at a time, copy should not happen.

//Validation for including text only from specified div

$('#DocumentText').mouseup(function (e) {
    debugger;
    isSelected = true;
    flaginclude = 1;

    // e.stopPropagation();
});

$(document).mouseup(function (e) {
    debugger;

    if (flaginclude != 1) {
        e.stopImmediatePropagation();
        isSelected = false;
    }
    flaginclude = 0;
});

myfunction()
{
 if(isSelected)
 {
   //logic to append selected text on div2
 }
}

Answer by Tim Down

You can alter the selection after the event to be limited to just a particular element. Here’s an example of how to get just text selected within a particular element:

http://stackoverflow.com/a/5801903/96100

Here’s an example function that uses my Rangy library to limit a selection:

Live demo: http://jsfiddle.net/nm3FM/

Code:

function limitSelectionToElement(el) {
    var selectedRange = null;
    var sel = rangy.getSelection();
    var elRange = rangy.createRange();
    elRange.selectNodeContents(el);
    if (sel.rangeCount) {
        selectedRange = sel.getRangeAt(0).intersection(elRange);
    }
    elRange.detach();
    sel.setSingleRange(selectedRange);
}

Answer by Starx

There is no dependable way to ensure this. However selection can be prevent on modern browsers using no-select.

#div1, #div2 {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

[Source]

Read more

How to ensure JPEG image is valid and can be handled by PHP?

Question by Nyxynyx

I have this JPEG that has been giving problems to the function imagesx($this->image) from the Resizer library that I am using. I am able to view the image using the browser, and when attempting to resize, I get the error:

imagesx() expects parameter 1 to be resource, boolean given

It is OK for me to not handle this file if it is going to throw an error. How can I use PHP to check whether this image can be handled properly by PHP’s image functions?


Code that calls the Library

// Download the photo
$img_content = file_get_contents($url);
if($img_content !== FALSE) {
    file_put_contents($img_documentroot . $img_subpath . $img_filename . '_tmp.jpg',
     $img_content);
}

echo $url . '<br>';
echo $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg<br>';
ob_flush();
flush();

// Resize photo
Resizer::open( $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg' )
->resize(300, 300, 'landscape' )
->save($img_documentroot . $img_subpath . $img_filename . '.jpg' , 90 );

// Thumbnail photo
Resizer::open( $img_documentroot . $img_subpath . $img_filename . '_tmp.jpg' )
->resize(100, 100, 'crop' )
->save($img_documentroot . $img_subpath . $img_filename . '.jpg' , 90 );

Output

I also echoed out the full path of the image being resized.

http://www.ApartmentsInAllstonMA.com/Images/Apts/132847_kn1.jpg
/home/photos/public_html/2012/0917/2516539_7_tmp.jpg
resource(127) of type (gd)
resource(130) of type (gd)
http://www.ApartmentsInMedford.com/Images/Apts/132847_lv2.jpg
/home/photos/public_html/2012/0917/2516539_11_tmp.jpg
resource(163) of type (gd)
resource(166) of type (gd)
http://www.AllstonApartmentX.com/images/agents/61.jpg
/home/photos/public_html/2012/0917/2516539_12_tmp.jpg
bool(false)

UPDATE

This is the code snippet that is causing the library to return a false value.

private function open_image( $file )
{

    // If $file isn't an array, we'll turn it into one
    if ( !is_array($file) ) {
        $file = array(
            'type'      => File::mime( strtolower(File::extension($file)) ),
            'tmp_name'  => $file
        );
    }

    $mime = $file['type'];
    $file_path = $file['tmp_name'];

    switch ( $mime )
    {
        case 'image/pjpeg': // IE6
        case File::mime('jpg'): $img = @imagecreatefromjpeg( $file_path );  break;
        case File::mime('gif'): $img = @imagecreatefromgif( $file_path );   break;
        case File::mime('png'): $img = @imagecreatefrompng( $file_path );   break;
        default:                $img = false;                               break;
    }

    return $img;
}

Answer by Starx

Checking for the mime type is a very good method to ensure the validity of JPEG image. Here is how you can do this.

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type
$type = finfo_file($finfo, $filename) . "n";  
if($type == "image/jpeg") { 
     //Valid JPEG Image
}
finfo_close($finfo);

According to your errors, you are sending boolean value instead of image resource.

Read more

Multiple Input fields with same id

Question by fahad

I am rendering data from php code with a input field but when i retrieve data from database the input field is replicated and i have assigned one id and one class value to it now i am facing that if i use id it only show me the 1st value only.if i use class it start iterating it and complete till each field and show empty where input fields are empty

Jquery Code is this

    $('.submit-button').on('click',function(){
       $('.datecontrol').each(function(){
       alert($(this).val());
   });

and my whole html is provided here

Answer by Starx

First, as per the title, it is not a good idea to use multiple fields with same id. It will create problems is CSS, Scripting, etc.

Next, if selecting certain numbers of field only is your problem, then assign a different class to the fields to represent a particular group.

Read more

jQuery Tweets Method

Question by Trt Trt

I have been trying this http://jsfiddle.net/pJgyu/26733/ which seems to work fine, but
when I copy paste my code in my rails 3.2 it doesn’t show anything! What is going wrong? I need to get the tweets from a user, so I need an easy way to do it! Also why does the “tweets” method does not exist in the jQuery API?

Answer by Starx

On the fiddle, there is an external script included so it is working there.

http://github.com/kerberoS/jQuery-Tweets/raw/master/js/jquery.tweets.0.1.js

If you want this to work on your code, you have to include the above script in your document too.


jQuery is a light weight JavaScript library, not a social networking toolkit, so it does not have any method as “tweets” in core library. However you can find plugins build for these specific reason, just like the one used in the fiddle you posted.

🙂

Read more

$.ajax() function working in IE but not in Chrome and FF

Question by icr

I guess this question is not asked in this forum before, tried searching alot but none matched or worked for me. Below is the JSFiddle link of code:

JSFiddle

Everything is working well in IE8 and IE9 but not in any other browsers. I tried looking for the problem in Chrome from which I got

XMLHttpRequest cannot load http://v3.actisku.com/GetUserPostData?pid=Test-37&surv=1170. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers

I tried searching for necessary solution i.e CORS but couldn’t figure out the solution. I am side by side looking for the same.

EDIT:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<html><head>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            var contents = $.ajax({
                url: 'http://v3.actisku.com/GetUserPostData?pid=Test-37',
                cache: false,
                crossDomain: true,
                dataType: 'html',
                data: { surv: '1170'},
                async: false
            }).responseText;

            var test = contents;
            alert(test);
            test = test.replace(/t/g, ';');
            alert(test);
            test = test.replace(/n/g, 'break');
            alert(test);
            $('#contentArea').attr('value', test);
        });
    </script>
</head>

<body>
<textarea id="contentArea" rows="10" cols="50"></textarea>
</body>
</html>​

Can we manually add headers so that the server feels like it is getting request from IE itself.

Regards,
icr

Answer by Starx

There is nothing in your code, to create Browser incompatibility. In fact they ware working fine in Firefox, and chrome. However, This seems unnecessary.

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}

As mentioned by Mahan, this looks to be like Server Configuration problem.

Read more

How do i change an element on Database update

Question by Varun Dhamija

Here’s an example of what i am doing :- i am populating the div with mysql database through php and there are two divs , clicking on Button (chat) hides the div 2nd div and clicking on (chat2) hides the first div and shows the second (using jquery)
(Both the divs are showing data of different tables )

Now what i want is when div1 is hidden and the database/table (that the hidden div is showing) is updated i want to change the css property of button(chat). I know that it can be done via Ajax but i am not very good at it , So please help me out.

and i am populating the div via Ajax .

enter image description here

Answer by Starx

I don’t think changing the CSS property has anything to do with AJAX. First you have make the AJAX request and when the request completes then you can do the update and change the CSS at the same time.

For example:

$.post("urltopost.php", { vartosend: 'value to send' }, function(data) {
    console.log(data); //Retrieve the data
    $("#div1").html(data); //Update the data

    //Change the css of the button now
    $("#div1button").css({ color: 'red' });
});
Read more
September 14, 2012

Uncaught ReferenceError: $ is not defined

Question by user1670671

I’ve been getting undefined error and I dont know how to fix it.

Here’s my code:

<script type="text/javascript">
    function returnBlurayDisc(member_id){
         var xmlhttp;

         if (window.XMLHttpRequest){
              xmlhttp=new XMLHttpRequest();
     }else{
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.onreadystatechange=function(){
          if (xmlhttp.readyState==4 && xmlhttp.status==200){
         document.getElementById("popup_container").innerHTML=xmlhttp.responseText;
         $("#GrayBackground").css({'height':'1900px','display':'inline'});

           }
     }

     xmlhttp.open("GET","ajax/returnAjax.php?member_id="+member_id+"&name="+name);
     xmlhttp.send();    
     }
</script>

The error is Uncaught ReferenceError: $ is not defined. Kindly help me.

Answer by Starx

$ in your code most probably refers to jQuery library. So, make sure you have included jQuery library file in your document.

If you use CDN then you have to include a similar tag like below on head section of your document.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

This includes the JQuery Library on your document and you can finally use the $ to target elements.

Read more

color in button background with css

Question by anc1revv

I’m building my navigation bar and I currently am using 3 images for each option on the menu.
I’m using css to replace the images based on when its non-selected, hovered, and selected.
Using html and css, i only knew how to highlight the actual words (ie home, order, how it works…), i couldn’t figure out a way to color in the whole box when selected.

Is there a way to do this with html/css without using image files?

enter image description here

Answer by Starx

So little information provided but still I will try assuming the most general way.

In a basic ul and li menu structure, like the following.

<ul>

    <li>

        <a href="#">Link Text</a>

    </li>

</ul>

The box surrounding all the menus are selected by simply

ul {
    /* Styles */
}

The box surrounding a menu item (probably what you are asking) is selected by ul > li

ul > li {   
    /* Style */
    background-color: red;
}

Note: You can also use ul li { ... } for more general way.

Where as, link itself is selected by ul > li a

ul > li a {
    /* Style */
}

Try to implement this on your case.

Read more
September 13, 2012

if else with an optional value

Question by Elliott

I can’t figure this out. I need to do and if else.

If A is not empty then it must equal B & C must = D & E must = F

It is the A & B part I think that has me messed up. I cant get it to work only if A is not empty

 if( ( !empty($data[0]) && trim($data[0]) == $_POST['firstname'] ) || trim($data[1]) == $_POST['lastname'] && $_POST['password'] == $password)

It is that A is optional that gets me.

Answer by andrewsi

Why do it all in one go?

If (A is not empty) then 
    if A == B && C == D && E == F then

Which I think comes out as:

if ( !empty($data[0]) {
   if ((trim($data[0]) == $_POST['firstname'] ) && trim($data[1]) == $_POST['lastname'] && $_POST['password'] == $password) {

Answer by Starx

It would be something like this:

if( !empty($a) && ($a==$b && $c == $d && e == $f)) {
 // Carry On
}
Read more
...

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