...

Hi! I’m Starx

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

Div tag displaying content in new line

Question by DeanGrobler

I have code that looks like this:

<h4 class="tableTotals">Total Selected: R<div id="bankTotal">##,##</div></h4>

The output that I want should all be in ONE line but as it turns out the div tags displays it’s content in a new line, which I don’t exactly want. So the output looks like this:

Total Selected: R
##,##

When I actually want it to display like this:

Total Selected: R##,##

Does anybody know how to stop the div displaying on a new line?
Thank for any push in the right direction!

Answer by David Houde

Use <span> instead of <div>

div is a block element, and h4 is a header meant for single line.

Answer by Starx

Style your div to be displayed as inline-block

#bankTotal { display: inline-block; }

Demo

Using inline-block does not have to chang the div completely into as inline element just like span . Furthermore, you can still have block properties.

Read more

Can you set event.data with jquery trigger

Question by 9-bits

With jquery .on() you can pass an optional parameter to set the event data. Can you do this with trigger as well?

Answer by Starx

I know an workaround we can use for this

$("button").on("click", function(event) {
   event.data = $(this).data('events'); // get the data value 
   alert(event.data); //use your data as you want
});


//Now set the data value and trigger
$("button").data('events','youreventsvalue').trigger("click");

Here is a demo

Read more

Shift centred div to the right

Question by Vince Lowe

I have a div called target which is centred and displayed over a google map when you pan to a map marker, i have since added a menu to the left of the map which means that when the google map pans to a marker it is no longer the centre of the screen.

I need to move the div to the right but I can’t seem to move it.

#target {
    position: fixed; 
    display: none; 
    width: 51px; 
    height: 51px; 
    top: 50%; 
    left: 50%; 
    margin: -40px 0 0 -26px; 
    background: url(../img/target.png) no-repeat center bottom; 
    z-index: 2;
}

Screenshot

Answer by Daniel K

You should be able to rectify your problem by playing a bit with the margin. Change the 4th value by adding a positive value so that it is greater than -26px. Such as:margin: -40px 0 0 20px;.

The 4th value in margin specifies the left margin value, which will shift your div to the right.

Alternatively

You can wrap the map and target div in a separate div from the menu, but you must change the target position value to relative or absolute instead of fixed:

<body>
    <div id="wrapper" style="position:relative;"> <!-- map and target wrapper div. make sure this is position: absolute OR relative so that positioning will reference this div. -->
        <div id="map">...</div>
        <div id="target"></div>
    </div>

    <div id="menu">
        ...
    </div>
</body>

With this alternate solution, the target and the map are aligned to the same div, almost as if they’re in their own window.

Answer by Starx

With your CSS, it is not possible to shift to the right. As it is what is forcing it to center

position: fixed;
left: 50%; /* be in the center */
top: 50%;

In order to change the position to the right, remove the left property and update you css to read the following.

right: 0;
top: 50%;
Read more

PHP shopping cart doesn't show numerous products

Question by Carla Dessi

i’ve made a php shopping cart, it shows all the products on the home screen, you can click on them and add them to your basket, then you are taken to the shopping cart screen. this only shows one product but with a quantity of how many different products you’ve added, even if they all have different titles. the total price and quantity work, its only the product name that doesn’t. This is my code..

<?php
session_start();
include "connect.php";
include "header.php";

function viewcart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
    $cart = $_SESSION['cart']; //store the cart array into a variable then display the content
    echo "<table border="1"><tr><th>Product Name</th><th>Quantity</th><th>Delete</th></tr>";
    foreach ($cart as $product=>$quantity){
        $q = "SELECT ID, Name FROM Products";
        $result = mysqli_query($_SESSION['conn'],$q);
        $row = mysqli_fetch_array($result);
        $product_id = $row[0];
        echo "<tr><td>$product</td><td>$quantity</td><td><a href="?action=delete&product=$product_id">-</a></td></tr>";
        mysqli_free_result($result);
    }
    echo "</table>";
    subtotal($cart); //display the subtotal
} else { //if shopping cart is empty
    echo "<p>There is no product in your shopping cart.</p>";
}


}

function addproduct($product_id, $product_qty){

$q = "SELECT ID, Name FROM Products";
$result = mysqli_query($_SESSION['conn'],$q)
 or die("Error: ".mysqli_error($_SESSION['conn']));
$row = mysqli_fetch_array($result);
$product_name = $row[1]; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
    $cart = $_SESSION['cart'];
    if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
        $cart[$product_name] += $product_qty;
    } 
    else { //otherwise, add new product-quantity pair to the array
        $cart[$product_name]=$product_qty;
    }
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
    $cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
    $_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}

function deleteproduct($product_id, $product_qty){

$q = "SELECT Name FROM Products";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['Name'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
    $cart = $_SESSION['cart'];
    if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
        $cart[$product_name] -= $product_qty;
        if ($cart[$product_name] == 0){ //if the quantity is 0, delete the key
            unset($cart[$product_name]);
        }
    }
    else { //exception
        echo "<p>Error!</p>";
    }
    $_SESSION['cart'] = $cart; //write the updated array back to session variable
} else {
    echo "<p>Error!</p>";
}
mysqli_free_result($result);
}

function emptycart(){

if (isset($_SESSION['cart'])){ //if shopping cart is not empty
    unset($_SESSION['cart']);
}
else {
    echo "<p>Error!</p>";
}
}


function subtotal($cart){ //calculate the total value of products in the shopping cart
$total = 0; //initialise total
if (!empty($cart)){
    foreach ($cart as $product => $quantity){
        $q = "SELECT ID, Price FROM Products";
        $result = mysqli_query($_SESSION['conn'],$q);
        $row = mysqli_fetch_array($result);
        $price = $row['Price'];
        $total += $price * $quantity;
    }
    echo "<p>Total: $total | <a href="?action=empty">Empty cart</a></p>";
} else {
    unset($_SESSION['cart']); //do not need to keep an empty cart, so delete it
    echo "<p>There is no product in your shopping cart.</p>";
}
}


if (isset($_GET['action'])){

if ($_GET['action']=='view'){

    viewcart();

} elseif ($_GET['action']=='add'){
    if (isset($_GET['product'])){
        $product_id = $_GET['product'];
        $product_qty = 1; //default product value
        addproduct($product_id, $product_qty);
        viewcart();
        echo "<p><a href="javascript:history.go(-1)">back</a></p>";
    } else {
        echo "<p>There is an error! Are you trying to attack this little poor shopping cart?</p>";
    }
} elseif ($_GET['action'] == 'delete'){
    if (isset($_GET['product'])){
        $product_id = $_GET['product'];
        $product_qty = 1; //default product value
        deleteproduct($product_id, $product_qty);
        viewcart();
    }
    else {
        echo "<p>There is an error! </p>";
    }
} elseif ($_GET['action']=='empty'){
    emptycart();
    viewcart();
} 

else {
    echo "<p>There is an error! </p>";
}
}
else {
    echo "<p>There is an error! </p>";
}


include "footer.php";

?>

Answer by Starx

You have a typo in your query. May be you wanted to extract the product id of the product, but, in fact selecting everything in a table.

$q = "SELECT ID, Name FROM Products";

Update it, to read something like the example below and check if this fixes the problem

$q = "SELECT ID, Name FROM `Products` WHERE name='$product' ";

And later you are reading the result as

$row = mysqli_fetch_array($result);

I hope you know that, this way $row will only get the first row it gets from the table.

Read more

.first('li) select first item in the list not working

Question by ScoVin

Hope you can help, this code is not working. It is selecting the next image ok, but if it is on the last image and there is no ‘next image’ then I want to select the first image in the ‘li’. I’ve added an if condition: if (nextLi.value !==”)… but this doesn’t seem to be working.

    function nextImg(){         
    $('#background').find('img').animate({'opacity': 0}, 500, function (){
        var nextLi = $('.sel').parent().parent().next('li').find('a');

        if (nextLi.value !=='') {
            var nextLiA = nextLi.attr('rel');
            $('#background').find('img').attr({'src':nextLiA});
            $('.sel').appendTo(nextLi); 
        } else {
            var nextLi = $('.sel').parent().parent().first('li').find('a');
            var nextLiA = nextLi.attr('rel');
            $('#background').find('img').attr({'src':nextLiA});
            $('.sel').appendTo(nextLi); 
        }
    });
}

Answer by Starx

Try this. It checks for the size of the li and if not found anything, selects the first.

function nextImg(){         
    $('#background').find('img').animate({'opacity': 0}, 500, function (){
        var li = $('.sel').parent().parent().next('li').find('a'); 

        if(li.length == 0) {
           //if there is not last item  
           li = $('.sel').parent().parent().first('li').find('a'); //get the first item
        } 
        var liA = li.attr('rel');
        $('#background').find('img').attr({'src':liA});
        $('.sel').appendTo(li); 

    });
}
Read more

UTF-8 text not fetching accurately in CodeIgniter php

Question by SarwarCSE

UTF-8 problem in CodeIgniter from mysql Problem

when i fetch utf data from mySql database using codeigniter active record then my text show like this

বাংলা নাম চেক করার জনà§à¦¯

actual text is

বাংলা নাম চেক করার জন্য

i have checked the config file

$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';

Without using Codeigniter i can show the text accurately in web site.

Answer by Starx

Make sure you have specified correct character set, in your html.

<meta http-equiv='Content-Type' content='Type=text/html; charset=utf-8'>

Make sure you have include the above meta tag in the top of your html.

In case of HTML5: use <meta charset='utf-8'>

Read more

Absolute position elements within iframe?

Question by Uzair Farooq

I want to absolute position an element in iframe relative to the document. I’m using this

.myClass
{
    position: absolute;
    top: 0;
    left: 0;
}

but it do not position the element at top left of document, it’s positioned at top left of the iframe.
How to apsolute position it to the document? jquery/javascript solutions are acceptable

Answer by Starx

Basically, in an iframe you load a different website or webpage.

The scripts, elements and CSS have to be controlled from within that page.

Read more

How To Avoid sql injections to existing code

Question by Maths Brain Teasers

There was a mysql injections on my website.It has 1000 of existing php files. From last 6 months , when i code i keep sure the code is injections free.But is there any solution how can i secure the legacy code without changing every file.

Answer by Starx

This is a very vast field. However, There are few points I can give you

  • Sanitize and filter every input you receive from the user.
  • Handle every errors correctly. Do not even leave one possibility of an error being triggered
    (This is a very important point and the main reason of most of the hacks)
  • If there were previous breaches, check the apache‘s log files to see where the injection happened. or where the hacking occur.
    1. There are mainly two types of logs file maintained in apache. access_log and error_log
    2. Once a breach occurs, make a backup of the logs and mitigate the problem, reviewing the logs.
  • If a documentation is available for the system you are maintaining currently, then the vulnerability can be detected quicker.

Some helpful references

  1. http://php.net/manual/en/security.database.sql-injection.php
  2. http://simon.net.nz/articles/protecting-mysql-sql-injection-attacks-using-php/

How hacking occurs?

Read more

Getting the height multiple elements aplying to siblings

Question by Christian Isai

I have this problem I dont know what im missing so far I have this code
I have a dropdown menu that inside has 1 big column and other 4 divs next to them, I have to make the other divs the same height of the first div.. I wrote this

$('.dropdown div:first-child').each(function(){
$this = $(this)
var $height = $this.height()
$(".dropdown div:first-child").siblings("div").css("height", $height)
});

the problem is that the variable $height is returning a 0 value.. do you know why Im not getting each height?

Thank you in advance

//edit

http://jsfiddle.net/DsBF2/

so you can have an Idea…

Answer by Henesnarfel

Check out your updated fiddle http://jsfiddle.net/DsBF2/1/

$('.dropdown div').each(function(){
    $this = $(this);
    var $height = $this.height();
    $this.siblings("div").css("height", $height);
});

UPDATE

This code would be better as the above goes through every child div unnecessarily

$('.dropdown').each(function(){    
    $this = $(this);
    var $div = $this.find("div:first-child");
    var $height = $div.height();
    $div.siblings("div").css("height", $height);
});

here http://jsfiddle.net/DsBF2/14/

Answer by Starx

Try the following code. It should do what you ask for.

var height = 0;
$('.dropdown div:first-child').each(function(k,v) {
    height = 0;
    $(this).siblings("div").each(function(k2,v2) {
        if(height == 0) { 
            height = $(this).height(); 
        }                       
    }).css('height', height);
});

Update

If you really want a trimmed out version, this should do it

$('.dropdown div').each(function(){
    var height = $(this).height();
    $(this).siblings("div").css("height", height);
});
Read more
March 5, 2012

jQuery Animation Conditional w/a Callback Function

Question by Andaero

EDIT BELLOW

How do I code the #west animation call on the #contentBox animation when it completes?

Basically I have a toggle button that animates/changes a div’s css and then to another div’s css once/after the first animation completes; then reverses the next time the toggle is executed.

Any help is appreciated. Thank-you.

The Conditional Statements:

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        });

        $west.animate({
            left : parseInt($west
                .css("left"), 10) == 0 
                ? -$west.outerWidth() 
                : 0
        });
   });

I went to the old fashoned way with out shorthanding the conditional statement

Answer by Andaero

I re-wrote the statement so it wasnt in shorthand and it works fine.

$("#menuToggle").click(

        function() {
            //var n = $("#west");
            var position = $("#west").offset();

            if (position.left == "0") {
                $("#west").animate({"left" : "-=300px"}, "slow")
                .animate({"width" : "1%"}, "fast", 
                    function() {
                    $("#contentBox").animate({"width" : "98%"}, "normal");
                });
            } else {
                $("#contentBox").animate({"width" : "70%"}, "normal", 
                    function() {
                    $("#west").animate({"width" : "30%"}, "fast")
                    .animate({"left" : "+=300px"}, "slow");
                });
            }
        });

Answer by Starx

You can always pass a callback function to the animate() method, which execuies once the animation is complete.

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        }, 5000, function() {
             //this is the callback part
            $west.animate({
                left : parseInt($west
                    .css("left"), 10) == 0 
                    ? -$west.outerWidth() 
                    : 0
            });
        });

   });
Read more
...

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