...

Hi! I’m Starx

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

CSS3 Responsive Layout – which method can i select?

Question by 3gwebtrain

HI i am making a website, this website having 3 different mockup for Desktop, tablets, Smartphones.. i can identifying the width using respond.js.

But i question is how can i switch the design to appropriate devices. i can change the width and height using query selectors, but how can i change the content of the page..

any good idea. In earlier i downloaded all contents and used to hide the unwanted content using display:none, i know this is wrong. which is the best way, apart from finding using server-side code?

thanks

Answer by Starx

I think it is wise to detect a mobile browser user agent string (server side) and display content accordingly.

If you are building using PHP, then check out this awesome script.

Usage is something like this:

if($isMobile){
   header('Location: http://m.youdomain.com/' . urlencode($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
   exit();
}

Also check out the Switcher

Read more

navigating between page divs with select and jquery mobile

Question by krapdagn

Trying to use this dropdown select to change to a different anchor on the page. It’s working except that when you select SF, it goes to the SF page and the selector button is set to SF. But if you then select NY, it goes back to #page1 but the default button stays as SF, unless the page is reloaded.

<select name="select1" id="select1" data-mini="true" data-native-menu="false" ONCHANGE="location = this.options[this.selectedIndex].value;">
<option value="#page1">New York, NY</option>
<option value="#SF">San Francisco, CA</option>
<option value="#LV">Las Vegas, NV</option>
<option value="#DAL">Dallas, TX</option>
</select>

What am I missing?

Thanks!

EDIT:

I think there is incomplete information here. On the #SF anchor text, for example, it’s an entirely new page with its own copy of the <select> in the header of that page. So what is happening is that when you select the second one to go back to the first, it doesn’t reset the first one.

Here is what the second select looks like:

<select name="select2" id="select2" data-mini="true" data-native-menu="false" ONCHANGE="window.location = this.options[this.selectedIndex].value;">
<option value="#SF">San Francisco, CA</option>
<option value="#page1">New York, NY</option>
<option value="#LV">Las Vegas, NV</option>
<option value="#DAL">Dallas, TX</option>

Here’s what happens

1 – Load #page1, NYC is preselected.
2 – Select SF, loads #SF, SF is selected because it is default in the second select
3 – Select NYC, it DOES load the NYC/#page1 page, but the select dropdown is still stuck on #SF because that was what it was last left at before the location changed.

Hopefully this more fully explains my problem. I’ve tried something like this (http://jsfiddle.net/QEUwg/132/) but it isn’t working, maybe because the two selects are in separate divs?

OK This works:

//refresh value         
$('select').selectmenu('refresh');

//refresh and force rebuild
$('select').selectmenu('refresh', true);

It only took about 20 hours of beating my head against the wall.

Answer by Starx

Use window.location instead of location

Update:

I will give you a better way since you are already using jQuery.

$("#select-choice-1").change(function() {
    $($(this).val())[0].scrollIntoView(true); 
})

Demo

Update 2

The problem is that you are using multiple select box and not updating all of them, when you are changing the page

$(".navigateToPage").on('change', function() {
    $(".navigateToPage").val($(this).val()); //set value for all the select boxes
    $(".navigateToPage").parent().find(".ui-btn-text").html($(this).find("option:selected").html()); 
    //^ Also find the text and update them

});

Working Solution

Read more

clean url not working with in a sub folder

Question by user1263260

I am developing a php web site. Here I have implemented clean URL using .htaccess file. I have successfully worked with clean URL but when I have created a sub folder named admin within the root folder htaccess is not working. So I have created another .htacess file inside the admin folder. See my code within the admin .htaccess

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^(.*).html$ $1.php [nc]
RewriteRule product/id/(.*)/ product.php?id=$1
RewriteRule product/id/(.*) product.php?id=$1   
RewriteRule ^(.*).htm$ $1.php [nc]

RewriteRule login/f/(.*)/ login.html?f=$1
RewriteRule login/f/(.*) login.html?f=$1    

I have attempted to log in the admin section, I have logged and my page redirected to the login page

header("location:login/f/".$fail);

URL rewriting is working but my page results in a wrong manner i.e. Images and css are not affected my redirected page

Why this happened?

On is it possible to use only one .htacess file, while will work in both the admin side and front end
Does any one help me Please
Thanks

Answer by Starx

This is the problem with the links which can find the proper resource. I am pretty sure, you are using relative links to the files like ../styles/page.css.

You have to assign the links of the CSSs, Scripts and Images in such a way that rewritten URL, do not have any effects.

The easiest way to solve this without indulging in any other complication is give direct links to files.

Example:

<link rel="stylesheet" href="http://mydomain.com/styles/page.css" />
Read more

Get the site status – up or down

Question by john

<?php
$host = 'http://google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
?>

I’m using the above program to get the status of site. But I always get an offline message.
Is there any mistake with the code?

Answer by stewe

The hostname does not contain http://, that is only the scheme for an URI.

Remove it and try this:

<?php
$host = 'google.com';
if($socket =@ fsockopen($host, 80, $errno, $errstr, 30)) {
echo 'online!';
fclose($socket);
} else {
echo 'offline.';
}
?>

Answer by Starx

What about a curl solution?

function checkOnline($domain) {
   $curlInit = curl_init($domain);
   curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
   curl_setopt($curlInit,CURLOPT_HEADER,true);
   curl_setopt($curlInit,CURLOPT_NOBODY,true);
   curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

   //get answer
   $response = curl_exec($curlInit);

   curl_close($curlInit);
   if ($response) return true;
   return false;
}
if(checkOnline('http://google.com')) { echo "yes"; }
Read more

Percentage to change div width in JS

Question by Dave

I have a very basic script that calculates and changes the width of a div but its not working it keeps giving a 100 % result .

My script is like this:

<script>
var hp = <? echo $row['hp']; ?>;
var max = <? echo $row['maxhp']; ?>;
var perc = Math.round(hp/max * 100);
if(perc > 100) perc = 100;
else if(perc < 0 ) perc = 0;
d = document.getElementById('health');
d.style.width= perc+"%";
</script>

<div id="health" style="background-color:green;min-height:5px;"></div>

The PHP numbers are showing correct in the JS as:

var hp = 500;
var max = 2500;

Any ideas why it might not be working ?

Answer by Derek

You have to wait until the document (DOM) to load first.

//head

$(function(){      //same as "onload" (jQuery)
    var hp = 500,
        max = 2500,
        perc = Math.round(hp/max * 100);
    if(perc > 100){
        perc = 100;
    }else if(perc < 0 ){
        perc = 0; 
    }
      //have to wait until DOM loaded, or else it return "not found"
    d = document.getElementById('health');
    d.style.width= perc+"%";
    alert(perc+"%");   
});​

DEMO: http://jsfiddle.net/DerekL/uUBVd/

enter image description here

Answer by Starx

Its working, see a demo

So, the problem is the script is running before the element is loaded on the DOM. Put the script after the HTML

<div id="health" style="background-color:green;min-height:5px;"></div>
<script>
var hp = <? echo $row['hp']; ?>;
var max = <? echo $row['maxhp']; ?>;
var perc = Math.round(hp/max * 100);
if(perc > 100) perc = 100;
else if(perc < 0 ) perc = 0;
d = document.getElementById('health');
d.style.width= perc+"%";
</script>
Read more

Vertically aligning a checkbox

Question by F21

I have looked at the different questions regarding this issue, but couldn’t find anything that works due to limitations in my markup.

My markup looks like so (unfortunately as this is generated by some backend, I am unable to change the markup).

<ul>        
    <li>
        <input type="checkbox" value="1" name="test[]" id="myid1">
        <label for="myid1">label1</label>
    </li>
    <li>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label for="myid2">label1</label>
    </li>
</ul>

I need the checkbox to be on the right and centered vertically in the <li>

Currently, this is styled as:

li input{
   display: inline-block;
   float: right;
   margin-right: 10px;
}

I have tried using various values for vertical-align, but that doesn’t seem to help. Also, in some cases the label can be very long and span multiple lines. The checkbox would still need to be able to vertically center itself when the height of the li is arbitrary.

How can I go about achieving this?

Answer by Supr

Vertical alignment only works on inline elements. If you float it, then I don’t think it is treated as part of that stream of inline elements any more.

Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):

input{
    width:20px;

    position:relative;
    left: 200px; 

    vertical-align:middle; 
}

label{  
    width:200px;       

    position:relative;
    left: -20px;

    display:inline-block;    
    vertical-align:middle; 
}

Answer by Starx

Its not a perfect solution, but a good workaround.

You need to assign your elements to behave as table with display: table-cell

Solution: Demo

HTML:

<ul>        
    <li>
        <div><input type="checkbox" value="1" name="test[]" id="myid1"></div>
        <div><label for="myid1">label1</label></div>
    </li>
    <li>
        <div><input type="checkbox" value="2" name="test[]" id="myid2"></div>
        <div><label for="myid2">label2</label></div>
    </li>
</ul>

CSS:

li div { display: table-cell; vertical-align: middle; }
Read more

Display a value of an array

Question by user1274113

I’m trying to get a specific value from a mysql_fletch_assoc array. I explain. Here is the database. Table: config with 2 fields: setting and value.

SETTING | VALUE
width | 100    
height | 50

And this is the query:

$result = (mysql_query("SELECT setting, value FROM config"));
while($setting = mysql_Fetch_assoc($result)){


    echo $setting['value'];
    echo "<br>";

Now i can see the entire array. I want to display every element individually. I tryed with $setting[‘value’][‘0’], $setting[‘value’][‘width’] with no success.

Edit: basically i want to do something like this:

echo $setting['value']['width'] gives -> 100 
echo $setting['value']['height'] gives -> 50

I hope that now it’s more clear

Answer by Starx

First, may be there is a typo error mysql_Fetch_assoc, fix this to mysql_fetch_assoc.

And In order to receive the values on your pattern, do the following

$setting = array();
while($row = mysql_fetch_assoc($result)) {
     $setting['value'][$row['setting']] = $row['value'];
}

Now, you can implement them as you want

echo $setting['value']['width']; // will give -> 100 
echo $setting['value']['height']; // will give -> 50
Read more

Difficulties implementing the JQuery Ui Slider

Question by CJS

I’ve implemented the jQuery slider UI in the page below but it doesn’t seem to be initialising.

Test Page

I loaded it up in Firebug and I got the following error:

$("#slider-range").slider is not a function
[Break On This Error]   

slide: function( event, ui ) {

Answer by Starx

You have not included the JQuery UI Library. Only included the jQuery is not enough.

You can use CDN to include the UI library.

  1. JQuery CDN:

    <script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>
    
  2. Google CDN:

    <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js' type='text/javascript'></script>
    

Include one of those, or, even better, read this Getting Started Docs.

UPDATES

You have to include the CSS files, to properly view the UI elements. Include the following CSS file

http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css

See your slider in action here

Read more
March 21, 2012

jQuery: How can I wrap <a> and </a> tags around existing images in a div?

Question by lith0pedion

I’m using slidy.js to cycle through several images inside a div.

My question is: How can I use jQuery to wrap <a href="http://www.google.com"> and </a> around each image in the div (whose id is “imgFade”)?

Thanks in advance!

Adam

Answer by Starx

Yes you can use the .wrap()

Example:

$("#yourdiv img").wrap('<a href="http://www.google.com" />');
                      // Note: the self closing pattern ^ THIS is how you should define the wrapping element

This is wrap a link around all the images inside the div with id="yourdiv"

Read more

Use jquery to re-populate form with JSON data

Question by jeffery_the_wind

I have an HTML form, that I save to the database via ajax. To get the query string of key/value pairs, I have used the very convenient serialize function, like this:

var myData = $("form#form_id").serialize();
$.ajax({
    url: "my_save_script.php",
    type: "post",
    data: myData,
    success: function(msg){
        alert(msg);
    }
});

Now I want to load a blank form, and re-populate it with the data from the database, which is delivered from an ajax call as a JSON string. I have been able to get a Javascript object with the correct key/value pairs like this:

data = $.parseJSON(data);
data = data[0];

What is the simplest, most elegant way to re-populate the form?

keep in mind the input elements of the form are text, select, checkbox, and radio. The names of the input elements are the same as the names of the database columns, and are the keys of the key/value pairs in the above data object. This is why the serialize function works so well for me

Answer by Bryan B.

I’d say the easiest way would be something along these lines:

// reset form values from json object
$.each(data, function(name, val){
    var $el = $('[name="'+name+'"]'),
        type = $el.attr('type');

    switch(type){
        case 'checkbox':
            $el.attr('checked', 'checked');
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').attr('checked', 'checked');
            break;
        default:
            $el.val(val);
    }
});

Basically, the only ones that are odd are the checkboxes and radios because they need to have their checked property, well, checked. The radios are a little more complex than the checkboxes because not only do we need to check them, we need to find the right ONE to check (using the value). Everything else (inputs, textareas, selectboxes, etc.) should just have its value set to the one that’s returned in the JSON object.

jsfiddle: http://jsfiddle.net/2xdkt/

Answer by Starx

I suggest you change the way you are making an ajax request. Use .post()

$.post("my_save_script.php", {
         data: myData,
    }, function(data) {
        $.each(data, function(i, item){
            $("#"+item.field).val(item.value);
        });      
    }, 
"json");
Read more
...

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