...

Hi! I’m Starx

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

Custom Highlight Failing on Website

Question by Matt

I’ve noticed on a lot of sites with custom highlight colors, if you press CTRL + A, the default highlight color, blue, always manages to creep through. Why is that? In making my own site, I have my own custom color too, but I also have the same problem. Does anyone know how to keep this from happening?

http://www.smashingmagazine.com/, http://www.admixweb.com/ are both examples of the CTRL + A problem.

Answer by Starx

Selection styles are mostly browser dependant, and might not be customisable in all browsers. Here is an example of how to configure such styles.

p.normal::selection {
    background:#cc0000;
    color:#fff;
}

p.moz::-moz-selection {
    background:#cc0000;
    color:#fff;
}

p.webkit::-webkit-selection {
    background:#cc0000;
    color:#fff;
}

Such styling are very risky to use and should not be depended upon.

Read more

Each div must increments its counter upon clicking

Question by Priya

I’ve three divs. Each div must increment its counter val upon clicking them.

HTML:

<body>
    <content>
        <div id="box1" class="v1" onclick="counter('box1')";>A : <span class="num">0</span></div>
        <div id="box2" class="v2" onclick="counter('box2')">B: <span class="num">0</span></div>
        <div id="box3" class="v3" onclick="counter('box3')">C: <span class="num">0</span></div>
    </content>
</body>​

Javascript:

  function counter(id){
     var id = document.getElementById(id);
     $('#id').click(function () {
          update($("span"));
     });
  }

  function update(j) {
     var n = parseInt(j.text(), 10);
     j.text(n + 1);
  }

Here is the code demo

Answer by Jeff B

You are doing a lot of work that jQuery would do for you. If you change your class to simply box and use the ID’s to style your content, you can do the whole thing like this:

<body>
    <content>
        <div id="box1" class="box">A: <span class="num">0</span></div>
        <div id="box2" class="box">B: <span class="num">0</span></div>
        <div id="box3" class="box">C: <span class="num">0</span></div>
    </content>
</body>

 

$( function() {
    $('.box').click( function() {
        var num = $(this).find('.num');
        num.text( parseInt(num.text()) + 1 );
    });       
});

Example: http://jsfiddle.net/ddvQU/1/

Some thoughts:

  • If a style is unique to a single element (now and in the future), you should be using IDs. Styles that are (or will be) common to multiple elements should use classes.

  • Using inline javascript onclick='blah()' is more difficult to manage, as it is not as easy to debug, does not allow for code reuse, and forces you to make updates in lots of places when you change code. It also makes you do nasty things like escaping quotes.

  • var id = document.getElementById(id); <= The whole reason we have jQuery is so that we don’t have to do this. Simply do $('#'+id). (ok, maybe not the whole reason, but one of them).

  • You don’t need to do the above if you attach a jQuery handler to your class of elements (see the first bullet). The handler will already have a reference to the object, even if it doesn’t even have an ID.

  • I would use .on() instead of .click(), but as you look to be new to jQuery, get this to work first, and then look into why on() is better, and how to do it.

Answer by Starx

There are many bugs in your script. Not to mentione, the markup selection is quite vague.

With a little update to some mark-ups, we can do this with a tiny snippet.

$(".clicable").click(function() {
    $(this).children("span").html(parseInt($(this).children("span").html()) + 1);
});

Check the demo here

Read more

Setting default anchor in jquery tools scrollable

Question by Ben Matewe

I am using jquery tools scrollable to create a 3 page site with a panoramic background (each background representing a page). I need the homepage to show as default. My current order is projects, home and contact and projects shows as default. I have tried using index.html#home but it doesn’t work. I am using horizontal scrolling.

My navigation menu is

<li><a href="#projects">Projects</a></li>
<li><a href="#home">Home</a></li>
<li><a href="#contact">Contact</a></li>

and my page code is:

<div id="browsable" class="scrollable"> 
<div class="projects"> ... </div>
<div class="home"> ... </div>
<div class="contact"> ... </div>

and this bit does my scrolling

$("#browsable").scrollable().navigator();

Answer by Starx

Defining links by href-"#projects" is wrong. Use as equals to (=) sign for that purpose.

<li><a href="#projects">Projects</a></li>
<li><a href="#home">Home</a></li>
<li><a href="#contact">Contact</a></li>

Your index.html#home should work now.

Read more

Getting the previous page GET parameters in PHP

Question by Alex

I have a range of similar pages that have a URL along the lines of www.mydomain.com/group?id=1.

From each of these pages there is a form that posts it’s values to the server. I need to work out what the id of the group was when the form is posted. I’m aware of being able to use $_SERVER['HTTP_REFERER'] and then maybe I could use a regex to get the id. However, I wondered if there was anything in PHP that would allow you to get the previous $_GET variables?

Alternatively, do people think it is a much better idea to store the current group id as a session variable?

Answer by Starx

Yes, Session is the way to go to . Store them and get the groups on every other page, using session . This is a proper way.


Despite, it is also possible to make $_GET available for every page. Using two ways (AFAIK).

  1. Create the exact same URL String with the parameters and send them along, as you are redirecting from page to page.

    • Or use functions like parse_url() to get only the query string and pass them along
  2. Use Session to back up the $_GET and reassign it to $_GET on every page. Put the below snippet or every page you redirect to.

    if(isset($_SESSION['GET_BACKUP']) { //Check if there was a backup before
         $_GET = $_SESSION['GET_BACKUP'];  //if yes use it
    }
    
    if(isset($_GET) && count($_GET)) { //if not and GET value is sent
         $_SESSION['GET_BACKUP'] = $_GET; //backup it
    }
    // Now use the get as you used to via $_GET
    

    Following this way, you will not get an attached data in the URL, which might be undesirable.


Update:

In case you are going with the second option, you should remember that the solution I provided is an demo and will not fit for more than one $_GET group. For multiple pages and storing their SESSIONS, you have to define separate keys to identify the backup. Kinda like

$_SESSION['mypage.php']['GET_BACKUP'] = $_GET;
Read more

PHP Forms – Numeric Value of Checkbox

Question by Patrick Appelman

I am creating an online order form for multiple products. I need to calculate the total cost for the products selected via checkbox and send it as a confirmation e-mail. The value of the checkbox is the price in dollars.

<input type="checkbox" id="product1" name="product1" value="100" />
<input type="checkbox" id="product2" name="product2" value="250" />

In my ‘process.php’ file, I need to total the cost for all items if they are checked.

if(isset($_POST['product1']) && $_POST['product1'] == '100') {
    $product1 = 100;
}

if(isset($_POST['product2']) && $_POST['product2'] == '250') {
    $product2 = 250;
}

$dollars = $product1 + $product2;

When I try to do it this way, $dollars is an empty variable “”. Can someone tell me how to fix this?

Thank you!

Answer by Starx

There is no syntactical error in your code. So the only explanation is that,

  1. $_POST[‘product1’] does not have value 100 or they are not sent through post at all
  2. $_POST[‘product2’] also does not have value 250 or they are not sent through post as well

In order to verify this, do a quick var_dump($_POST) at the top of your .php file

Read more

Problems transferring variables into ob

Question by rix

I use the following code to read a template into the buffer (ob). $vars contains all the variables i want to have access to in the template.

print_r($this->vals);  //prints out an array of values, value1 => '', value2 => ''...
ob_start();
include myTemplate.php
$content = ob_get_contents();
ob_end_clean();
echo $content;

But then in my template $vals is undefined or i don’t have access to it.

Any idea where I’m going wrong?

Thanks,

Answer by Starx

May be a simple typo error. But you are using $vals instead of $vars.

And if this is not the problem put ob_start() at top.

ob_start();
print_r($this->vals);  //prints out an array of values, value1 => '', value2 => ''...
include "myTemplate.php"; //few errors were here, no quotes and semicolon
$content = ob_get_contents();
ob_end_clean();
echo $content;

Just did a quick test, it works.


Update

In case you are trying to get the value of print_r($this -> vals) to $content. There is a very easy way to do this. print_r()[docs] function take another argument as well whether to return or not.

If so, your entire code comes down to this

$content = print_r($this->vals, true); 
Read more

jQuery: Select last match before specified element

Question by rampion

Is there a way in jQuery to, given an element and a selector, select the last match of that selector before that element from an in-order traversal of the DOM tree?

For example, given the DOM tree:

<html>
  <body>
    <div class="a" id="div0" />
    <div>
      <div class="a" id="div1"/>
    </div>
    <div class="b" id="div2"/>
    <div id="element"/>
    <div class="a" id="div3"/>
    <div class="b" id="div4"/>
  </body>
</html>

Using the selector .a and element #element, you’d get #div1, and using the selector .b and the element #element, you’d get #div2.

The use case is writing a GreaseMonkey script to work across different versions of Firefox with some slightly mangled HTML. I’ve got an element I can find consistently in all versions, but another element I want to find is either a previous sibling of an ancestor of the element or a descendent of a previous sibling of an ancestor of the element (depending on the version).

All I can really rely on is that it is the last match of the selector that occurs before the element I have when doing an in-order traversal of the DOM tree.

Answer by James Montagne

This should do it, using your first example:

var $collection = $(".a, #element");

var eleIndex = $collection.index($("#element"));

var prevEl = $collection.eq(eleIndex - 1);

alert(prevEl.attr("id"));

http://jsfiddle.net/WdsGa/

Answer by Starx

This should do it

var last = $(".a, #element").eq($(".a, #element").length-1);
Read more

Multiple file upload using javascript without modifying current code

Question by Uffo

I have a script already for uploading pictures, but I want the ability to select more pictures at once on upload,by holding down ctrl,I know I can use uploadify but I don’t want to start over, mabe you guys know a script or something for jquery, that will work without to remove the current code, or you guys could give me a snippet.

Answer by Starx

The ability to slect multiple files in entirely the browsers features. Which cannot be changed by using a Javascript or css or html. Using uploadify or similar as you mentioned in your question is the right way to go.

You know uploadify also uses the swfobject.js, to overcome this limitation by using an actionscript instead.

Read more

Where do I put database config values in Codeigniter?

Question by MotiveKyle

I am trying to connect to a different database than what is in my database config file.

I’ve been able to do this with the following in my model:

        $wp['hostname'] = "localhost";
        $wp['username'] = "root";
        $wp['password'] = "";
        $wp['database'] = "transfer";
        $wp['dbdriver'] = "mysql";
        $wp['dbprefix'] = "";
        $wp['pconnect'] = FALSE;
        $wp['db_debug'] = TRUE;
        $wp['cache_on'] = FALSE;
        $wp['cachedir'] = "";
        $wp['char_set'] = "utf8";
        $wp['dbcollat'] = "utf8_general_ci";

        $wpDB = $this->load->database($wp, TRUE);

and then running queries like so: $query = $wpDB->get();

I can only get it to work when the config values are in the model itself (so there would be a lot of duplication). I’ve tried putting the config array in the constructor, but I get an error that it can’t find it.

Where can I put the config array so I don’t have to duplicate it and that’s available throughout the model?

Answer by Wesley Murch

Database configuration usually goes in config/database.php. You can configure multiple database connections and store them with different group names:

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'host1';
$db['default']['username'] = 'user1';
$db['default']['password'] = '******';
$db['default']['database'] = 'my_db';

$db['other']['hostname'] = 'host2';
$db['other']['username'] = 'user2';
$db['other']['password'] = '******';
$db['other']['database'] = 'my_other_db;

The $active_group refers to the default group when the database class is loaded. To connect to another group in your model, you can use this in the model’s __construct method:

$this->db = $this->load->database('other', TRUE);

While this doesn’t play nicely with the more flexible $this->load->model('model_name', 'alias', $config) approach, it might be easier.

More info: http://codeigniter.com/user_guide/database/connecting.html

Answer by Starx

Since your config data appears to be database related, store them in

system/application/config/database.php

Read more

Session variables seem not to be saved

Question by Putnik

Quite simple code:

<?
session_start();
$_SESSION['t'.time()]     = "ok";
echo "<pre>".print_r($_SESSION, 1)."</pre>";
?>

shows, as expected, something like

Array
(
    [t1330966834] => ok
    [t1330966835] => ok
    [t1330966836] => ok
)

after 3page reloads.

Let’s change a few symbols:

$_SESSION[time()]     = "ok";

(now without ‘t’) and I expect after few reloads something like

Array
(
    [t1330966834] => ok
    [t1330966835] => ok
    [t1330966836] => ok
    [1330967020] => ok
    [1330967021] => ok
    [1330967022] => ok
    [1330967023] => ok
)

But actually the result is absolutely different:

   Array
    (
        [t1330966834] => ok
        [t1330966835] => ok
        [t1330966836] => ok
        [1330967020] => ok
    )

We have 3 previous array cells ad one and only one ‘time’ cell – no matter how many times you reload the page. The time is correct, it different each second but only one cell without ‘t’!
Also I tried

$t =time();
$_SESSION[$t]     = "ok";

and even

$t =intval(time());
$_SESSION[$t]     = "ok";

But it’s remains only one cell with time.

Tested at php 5.2.13 and 5.3.10 at 2 different servers.
What am I doing wrong?

Answer by juanrpozo

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

http://php.net/manual/en/session.examples.basic.php

Answer by Starx

This is not a strange thing. It is simply skipping numeric keys. You can see this error, if you have enabled the notice to be displayed.

As mentioned on this comment on php.net. You should not use numeric keys to define values in session.

Quote

Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;) or you will get the error “Notice: Unknown: Skipping numeric key 0. in Unknown on line 0”

Read more
...

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