...

Hi! I’m Starx

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

toggle div color on click

Question by user348173

I have the following JS:

 $(".place").mouseover(function () {
            $(this).css('background-color', '#00cc00'); // green color
        }).mouseout(function () {
            $(this).css('background-color', '#336699'); // light blue color
        });

When mouse is over then div become green. I want when user clicks on div then div persist green color. If they click again then set color to light blue. How can I do this?
Thanks.

Answer by Starx

Use .toggleClass() function instead.

Usage:

$(".place").click(function () {
   $(this).toggleClass("green");
});

Initially give background-color: #336699 and override this style later on with the toggleClass().

Your CSS should look something like this.

.place { background-color: #336699; }
.place:hover, .place.green { background-color: #00cc00; }

See this in action here.

Updates:


Update 1: Demo with the green in hover .

Read more
March 14, 2012

Styling using Javascript Cookie

Question by Tim D'Haene

I seem to be able to retrieve the value of the cookie but the style of the corresponding ID isn’t changed. What am I missing?

    function getCookie(name) {
        var cookieName = document.cookie;
        var prefix = name + "=";
        var begin = cookieName.indexOf("; " + prefix);
        if (begin == -1) {
            begin = cookieName.indexOf(prefix);
            if (begin != 0) return null;
        } else begin += 2;
        var end = cookieName.indexOf(";", begin);
        if (end == -1) end = cookieName.length;
        return unescape(cookieName.substring(begin + prefix.length, end));
    }
    var value = getCookie('nameCookie');
    document.getElementById(value).style.height = "10%";

following code also doesn’t work

    var value = getCookie('nameCookie');
    if (value == 'test') {
          document.getElementById('test').style.height = "10%";
    }

Answer by Starx

Since you seem to be able to retrieve the value of the cookie
the problem is that when the code is running, it cannot find the element because the DOM is not ready yet. Make sure the script is running, after the element is loaded.

Just place your script block just before closing the </body>.

Read more

Dynamic text in textarea – getting value

Question by Gabriel Żukowski

My text/value in textarea it’s not static – I’m chaning it. I can’t get the current value.
E.g
1

<textarea>
Lorem ipsum
</textarea>
//it's defalut in html file

2

Putting into textarea:

Dolores is lorem ipsum

Alert is only showing 1 version(“lorem ipsum”), but not second (“Dolores is lorem ipsum”). I’m trying to do it in jquery:

var variable = $("#selector").val();
alert(variable);

What I’m doing wrong?

EDIT

I want to catch it to variable 🙂 Not to alert. Alert is only my test 🙂

Answer by TimWickstrom.com

var text = $('#textareaID').val();

$('#textareaID').change(function() {
  text = $(this).val();
});

when ever you want text just reference it 🙂

EDIT:

If your using tabs UI please review the docs and the event management:

Place This outside of bound scope:
var text = $('#textareaID').val(); OR var text = '';

$('#example').bind('tabsselect', function(event, ui) {
      // Objects available in the function context:
      // ui.tab anchor element of the selected (clicked) tab
      // ui.panel element, that contains the selected/clicked tab contents
      // ui.index zero-based index of the selected (clicked) tab
      // INSIDE HERE IS WHERE YOU CAN PUT THE CODE IN THE ABOVE EXAMPLE
      $('#textareaID').change(function() {
            text = $(this).val();
      });
});

NOTE: $(‘#example’) would be the parent div that holds the tabs and content

Further optimization recommendation.

If you think $(‘#textareaID’) will be called often you may want to cache a reference to it so the selector engine does not have to find it on every instance, this would be done like:

var textarea = $('#textareaID');
 var text = $('#textareaID').val();

For this line:

var textarea = $('#textareaID');

Make sure it is inside of a $(document).ready(function() {}); Call and the element is exists

you could check for this by doing:

var textarea = $('#textareaID') || false;

And wrap the code above like this:

$('#example').bind('tabsselect', function(event, ui) {
          // Objects available in the function context:
          // ui.tab anchor element of the selected (clicked) tab
          // ui.panel element, that contains the selected/clicked tab contents
          // ui.index zero-based index of the selected (clicked) tab
          // INSIDE HERE IS WHERE YOU CAN PUT THE CODE IN THE ABOVE EXAMPLE

          if(textarea) {
               textarea.change(function() {
                    text = $(this).val();
               });
          }
    });

Hope this helps!

Answer by Starx

The error is somewhere else.

The code you are using is correct. Check a demo

Read more

jQuery not loading in DOM Window

Question by user1048676

All,
I’ve got the following code:

$(document).ready(function() {
// more code using $ as alias to jQuery
alert('it works');
},'jQuery');

When the page loads I get the following error:

Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function

I’ve loaded jQuery before I tried to add this.

Here is how this was loaded (my code is the custom.js):

<script type='text/javascript' src='http://localhost/oml_live_update/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/plugins/prettyphoto/js/jquery.prettyPhoto.js?ver=3.1.3'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/superfish.js?ver=1.4.8'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/flexslider.js?ver=1.8'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/framework/frontend/assets/js/roundabout.js?ver=1.1'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/assets/js/alyeska.min.js?ver=1.0'></script>
<script type='text/javascript' src='http://localhost/oml_live_update/wp-content/themes/alyeska/assets/js/custom.js?ver=1.0'></script>

Any ideas on why this won’t work?

Answer by Jasper

$(function() {
    alert('it works');
});

Does that not work for you? This is a standard syntax for this: http://api.jquery.com/ready/

If you want to create an IIFE (immediately invoked function expression):

(function ($) {
    alert('it works');
})(jQuery);

This creates a new scope for the code within and passes in the jQuery object as $.

Update

I don’t use WordPress but my understanding is that $j=jQuery.noConflict(); is run, so jQuery is basically stored in the $j variable (if it isn’t done automatically then it needs to be done manually):

<script type='text/javascript' src='http://localhost/oml_live_update/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$j = jQuery.noConflict();
$j(function () {
    alert('it works');
});
</script>
...

Also note that you can pass $ into the anonymous function that is the document.ready event handler so you don’t have to use $j:

$j(function ($) {
    alert('it works');
    //you can now use $() instead of $j()
});

Update

Have you tried using jQuery in place of $?

jQuery(function($) {
    alert('it works');
    //since `$` was passed into this function, it can be used instead of `jQuery`
});

Answer by Starx

The problem is probably the conflicting versions. Use

<script>
    $.noConflict();
    $(document).ready(function() {
    // more code using $ as alias to jQuery
    alert('it works');
    }); //You dont need to pass the pass the extra 'jQuery' Parameter
</script>
Read more

jQuery Submit will not submit form

Question by Prince

I have a for that I am submitting with this button:

<button id="registerButton" type="submit" name="submit" style="margin-left: 300px;">Click to Complete</button>

I am doing error checking with this jQuery:

$('#registerButton').bind('click',function(){
    if($('#formElem').data('errors')){
            alert('Please correct the errors in the Form');
            return false;
        }
});

When I go to submit the form it will pop up with the alert if there are errors detected on the form. However, if there are no errors the button doesn’t do anything. What am I doing wrong?

Answer by Starx

Bind the validation on the submit event of the form.

$("#formid").submit(function(e) { 
    if($(this).data('errors')){
        //display error
        e.preventDefault(); //stop the submit
    } else {
       //do something or nothing
       //but it will submit the form
    }

});
Read more

css html tables left and right border

Question by user1245706

I’m trying to write some css that will make it so my html table only has borders horizontally, and no borders vertically in between columns.

here is what i have so far:

@charset "utf-8";
/* CSS Document */

<style type="text/css">

box-table-a{
    font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
    font-size: 12px;
    margin: 45px;
    width: 480px;
    text-align: left;
    /*border-width: 0px;
    border-left: 0px;
    border-right: 0px;*/
    border-collapse: collapse;
}

#box-table-a th{
    font-size: 13px;
    font-weight: normal;
    padding: 8px;
    background: #b9c9fe;
    border-right:1px solid #b9c9fe;
    border-left:1px solid #b9c9fe;
    border-top: 4px solid #aabcfe;
    border-bottom: 1px solid #fff;
    color: #039;
}
#box-table-a td{
    padding: 8px;
    background: #e8edff; 
    border-bottom: 1px solid #fff;
    color: #669;
    border-top: 1px solid transparent;
}
#box-table-a tr:hover td{
    background: #d0dafd;
    color: #339;
}
</style>

This results in a table with white borders on all sides. Any ideas what I’m doing wrong?

EDIT
I can get it to do what I want here: http://jsfiddle.net/QZwt5/26/
but when I take this exact table, and exact css into dreamweaver and then ftp to my server I am still getting thin white lines in-between each cell.
image

Also just noticed that if I turn off normalized in fiddle that the borders appear on the table there.

Everything is running on an ubuntu server, I’m building it in winXP and then ftp to apache, so there might be some permission problems interfering with the CSS?

Answer by Starx

I think this is enough

table tr { border: 1px #000 solid; }

Demo

Read more

SQL query error, need some assistance

Question by Clavus

I’ve got this query that should refund people half the stuff they bought in the past week:

UPDATE main_data SET md.amount_current = md.amount_current + (bought.total / 2) 
FROM main_data AS md 
INNER JOIN (
    SELECT DISTINCT sb.user_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id
) AS bought ON bought.user_id = md.user_id 
WHERE md.valid = 1

The SELECT part executes just fine on its own and returns the right data (IDs that should be refunded and how much they spend in that week). However the query as a whole throws an error saying I have an error in my SQL syntax near line 2 (I quote: ‘FROM main_data AS md INNER JOIN ( SELECT DISTINCT sb.forum_id, SUM(sb.s’).

I can’t see what I’m doing wrong.

Answer by Michael Fredrickson

MySql uses a different syntax for join with update statements than what you’re using above. Try changing your query to:

UPDATE main_data md 
INNER JOIN (
    SELECT DISTINCT sb.user_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id
) bought ON bought.user_id = md.user_id 
SET amount_current = md.amount_current - (bought.total / 2) 
WHERE md.valid = 1

Note, I changed

SET amount_current = md.amount_current + (bought.total / 2) 

To subtract instead of add:

SET amount_current = md.amount_current - (bought.total / 2) 

Answer by Starx

There is no user_Id inside the INNER JOIN

UPDATE main_data SET md.amount_current = md.amount_current + (bought.total / 2) 
FROM main_data AS md 
INNER JOIN (
    SELECT sb.user_id, DISTINCT sb.forum_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id
) AS bought ON bought.user_id = md.user_id 
WHERE md.valid = 1
Read more

variable key name

Question by thelolcat

Can I check for a variable key without using a temporary variable.

$var = 'blabla';
$key = "{$var}_abc";

if(isset($someobject->$key))...

?

with arrays you can do this… $array[“{$var}_abc”]

Answer by salathe

Yes. You can use curly braces containing an expression resulting in a string, where that string is the name of the property you want to check.

$someobject->{"{$var}_abc"}
$someobject->{$var."_abc"}

Answer by Starx

You can do this, using property_exists() method

if(property_exists($object, $var."_abc")) {
 // do stuff
}
Read more

php mysql group by date with yyyy-mm-dd format

Question by porfuse

I had a mysql table called events with the fields: id, date, and name.
The date field has the format yyyy-mm-dd hh::mm:ss edit: meaning it is in datetime format

I want to group the events by day, and I wasn’t sure how to approach this- is there a way to select only the month and day from the field? or should i use PHP after I select all the “events”

my end goal is to have something like this:

March 10th: 
  event1, 
  event2
March 11th: 
  event4, 
  event5

I found MySQL select using datetime, group by date only but I’m not sure how to implement it:

SELECT DATE_FORMAT(date, '%H%i'), DATE_FORMAT(date, '%M %D'), name FROM events ORDER BY date

Thanks!

EDIT:

ended up using this:

$sql = “select team1, team2, DATE_FORMAT(date,’%Y-%m-%d’) as created_day FROM games WHERE attack = ‘1’ GROUP BY created_day”;
$result = mysql_query($sql);
$curDate = “”;

    while (list($team1, $team2, $date) = mysql_fetch_row($result))
    {
      if ($date != $curDate)
      {
        echo "$date --------n";
        $curDate = $date;
      }

      echo "game data: $team1 $team2";
    }

Answer by Kharaone

You should indeed use php to get this done. But since most of current system sepate logic from display, I’d use only one pass and not (NUMBER OF DAYS + 1) SELECTs, and prepare an array that I can reuse later for my display.

$query = "SELECT DATE_FORMAT(date, '%M %D') as d, name FROM yourtable ORDER BY date";
$foo=array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
    //some logic to test if it's safe to add the name
    $foo[$row['d']][]=$row['name'];

}

And then when i’d need it (through a template or your “view”)

foreach($foo as $date => $events) {
    echo $date . ":nt";          
    echo implode(",nt", $events);
    echo "n";
}

so it fits the format you set to yourself.

Hope that helped

Answer by Starx

If you use group by you will not get one row out of it. So the way you want is not possible through Group By AFAIK.

$query = "SELECT distinct(DATE_FORMAT(date, '%M %D')) as d FROM yourtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
   echo $row['d']
   $sql = "SELECT * FROM yourtable WHERE DATE_FORMAT(date, '%M %D')='$row[d]'";
   $rs = mysql_query($query);
   while($r = mysql_fetch_assoc($rs)) {   
      echo "event";
   }
}
Read more

How to count # words in a textarea

Question by Yuliang Han

I am wondering whether there is any javascript and PHP code to count number of words which are encoded in unicode.

Answer by Starx

Picked out from the php.net’s manual

function str_word_count_utf8($str) {
  return count(preg_split('~[^p{L}p{N}']+~u',$str));
}

As it is quoted

If the pattern contains utf-8, utf8_encode() the pattern,
as it is expected to be valid utf-8 (using the u modifier).

Read more
...

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