September 28, 2011

CSS Multiple grouped elements with margins

Question by Marty Wallace

Take this HTML:

<div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
</div>

With the companion CSS:

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px;
    background: red;
}

The result of this is four blocks, which have between them 2 pixels of space (1px from the right margin of the left block and 1px from the left margin of the right block).

Is there a way that I can achieve a similar effect to border-collapse? ie. I want there to be only one pixel of margin between adjacent blocks.

This is a basic example of often more complex situations that I run into, and I don’t want to get around it by by anything similar to only setting margin-left to 1 pixel etc.

Answer by Starx

There are multiple ways to this

One of them is

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px 1px 1px 0;
    background: red;
}
div.block:last-child {
    margin: 1px 0 1px 0;
}

Another is

div.block+div.block { margin-left: 1px; }

You can check the demo of both way here

September 26, 2011

How can I change the text of a <span> element?

Question by Sheehan Alam

I have a toggle button that I’m adding to an iFrame:

<script>
    $('#list div').each(function(){
        $(this).append('<span class="togglebutton">Maximize</span>');   
    });

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
    });
</script>

How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?

Answer by jondavidjohn

$("span.togglebutton").click(function() {
    var $this = $(this);  // cache jquerized 'this'
    $this.closest("li").children("div").toggleClass("maximized");

    var currentText = $this.text();

    // if the text is currently "Maximize"
    if (currentText === "Maximize") {
        // change it to new value
        $this.text("New Text");
    }
    else {
        // change it back to "Maximize"
        $this.text("Maximize");
    }
});

Answer by Starx

Well, if you are looking for some function like toogleClass() to do that job for you, you are out of luck. AFAIK, you have to do it manually.

Do something like this

function toggleText() {
    var curText = $("span.togglebutton").text();
    var newText;
    if(curText=="Maximize") { newText = "Minimize"; }
    else { newText = "Maximize"; }
    $("span.togglebutton").text(newText);
}

Now you can call it happily where you want to toggle it. Like

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
        toggleText();
    });

Why isn't my button click event being triggered?

Question by Sheehan Alam

I have the following js file:

var IOMaximizeButton = {
 setup: function () {
    $(this).click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

$(document).ready(function() {
  IOMaximizeButton.setup();
});

Here is the body of my HTML:

 <body>
    <a href="#" data-role="button" data-icon="delete">Maximize</a>
    <iframe id='iframe-primary' name='iframe-primary' src='foo.html' />
    <iframe id='iframe-secondary' name='iframe-secondary' src='bar.html' />
    </body>

I want that javascript to execute when my button is clicked. But it doesn’t seem to be triggering. Why?

I have imported my JS file at the bottom of the HTML page btw.

Answer by James Allardice

In your object, this refers to the instance of the object itself, so you’re trying to bind a click event to the JavaScript object, rather than a DOM element. I’m guessing you actually want something like this:

var IOMaximizeButton = {
 setup: function () {
    $("#yourButton").click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

Here’s a working example.

Answer by Starx

Your function is not attached to any selector, so I cannot catch any events. $(this) is a blank object.

Try changing $(this) to some specific selectors.

Redirecting a page using Javascript, like PHP's Header->Location

Question by Keith Donegan

I have some code like so:

$('.entry a:first').click(function()
{
    <?php header("Location:" . "http://www.google.com"); ?>
});

I would like to know how I can achieve this using Javascript.

Answer by Starx

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

Are there any essential reasons to use isset() over @ in php

Question by Tchalvak

So I’m working on cleanup of a horrible codebase, and I’m slowly moving to full error reporting.

It’s an arduous process, with hundreds of notices along the lines of:

Notice: Undefined index: incoming in /path/to/code/somescript.php on line 18

due to uses of variables assuming undefined variables will just process as false, like:

if($_SESSION['incoming']){
    // do something
}

The goal is to be able to know when a incorrectly undefined variable introduced, the ability to use strict error/notice checking, as the first stage in a refactoring process that -will- eventually include rewriting of the spots of code that rely on standard input arrays in this way. There are two ways that I know of to replace a variable that may or may not be defined
in a way that suppresses notices if it isn’t yet defined.

It is rather clean to just replace instances of a variable like $_REQUEST['incoming'] that are only looking for truthy values with

@$_REQUEST['incoming'].

It is quite dirty to replace instances of a variable like $_REQUEST['incoming'] with the “standard” test, which is

(isset($_REQUEST['incoming'])? $_REQUEST['incoming'] : null)

And you’re adding a ternary/inline if, which is problematic because you can actually nest parens differently in complex code and totaly change the behavior.

So…. …is there any unacceptable aspect to use of the @ error suppression symbol compared to using (isset($something)? $something : null) ?

Edit: To be as clear as possible, I’m not comparing “rewriting the code to be good” to “@”, that’s a stage later in this process due to the added complexity of real refactoring. I’m only comparing the two ways (there may be others) that I know of to replace $undefined_variable with a non-notice-throwing version, for now.

Answer by user187291

Another option, which seems to work well with lame code that uses “superglobals” all over the place, is to wrap the globals in dedicated array objects, with more or less sensible [] behaviour:

class _myArray implements ArrayAccess, Countable, IteratorAggregate
{
     function __construct($a) {
       $this->a = $a;
     }

    // do your SPL homework here: offsetExists, offsetSet etc

    function offsetGet($k) { 
        return isset($this->a[$k]) ? $this->a[$k] : null;
        // and maybe log it or whatever
    }
}

and then

 $_REQUEST = new _myArray($_REQUEST);

This way you get back control over “$REQUEST” and friends, and can watch how the rest of code uses them.

Answer by Starx

You answered you question yourself. It suppress error, does not debug it.

September 21, 2011

How to know route from the URL or $request Object?

Question by mrN

PLOT:

After implementing ACL on my website, if a user tries to access unauthorised page he will be denied and shown a page to login. After he loggs in, I wanted to redirect the user to the previous page to which he was denied to earlier.

To do this, I store the request parameters using $request -> getParams(), onto a session variable, which will be used to generate the url again. This is where the problem occurs, to generate the url back, I need the name of the route and that i dont know how to read.

I need to know the route name, so that I will be able to regenerate the url, from the array stored in session, or if there is a better way to solve this, please suggest.

Answer by Starx

Dont try to think of complex solutions for simple problem.

You can do this, with just using $_SERVER['REQUEST_URI'], this gives the same result as @Phil’s answer (Correct me, If i am missing something). and is more than enough to do what you want.

September 14, 2011

.getSelection()

Question by Jean

HTML code–

<script language="javascript" type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script language="javascript" type="text/javascript" src="js/jquery.field.selection.js"></script>

    <div id="copy">Copy</div>
        <textarea....id="t">

jquery—

$(docu.....
$('#copy').click(function(){
var range = $('#TextArea').getSelection();
alert(range.text);
});

});

When the #copy button is pressed the alert does not show the selected text in #t. It comes in blank.

I need the selected text from the textarea

Answer by Starx

Your code is not running because, this statement fails

var range = $('#TextArea').getSelection();

There is nothing as TextArea as ID in the markup you provided, so the script encounters an error and does not continue beyond it.

If you place the alert at the top part, I am sure the alert box will pop up.
i.e

$('#copy').click(function(){
    alert(''); //this will work
    var range = $('#TextArea').getSelection();
    alert(range.text);
});

if mouse on hover of div then display menu

Question by PD24

I have the following menu which cascades on hover but i need to add some conditional checks like if the mouse is on hover on the div then keep the menu sliding down.

Also if the mouse is hovered on the LI then check them menu down.

As you can see it just slides down and back up once you leave the “div”.

Im stuck… and have tried for hours searching for if statements etc, i just cant get the syntax correct.

my example

Answer by ShadowScripter

Here is a working example

HTML

<div id="leftWrap">
    <div id='accordion'>
        <ul>
           <li><div>Absorption</div>
               <ul style="display: none;">
                   <li>Accessories</a>
                       <ul style="display: none;">
                           <li>AA500AFG</li>
                           <li>AA500F</li>
                           <li>AA500G</li>
                           <li>AA990F</li>
                       </ul>
                   </li>
                   <li>Consumables</li>
                   <li>Products</li>
               </ul>
           </li>
           <li><div>Fluorescence</div>
               <ul style="display: none;">
                   <li>Accessories</li>
                   <li>Consumables</li>
                   <li>Products</li>
               </ul>
           </li>
       </ul>
    </div>
</div>

Javascript/JQuery

jQuery(document).ready(function() {
    $('#accordion ul > li').hover(function() {
        $(this).children("ul").slideToggle('slow');
    });
});

If you ask me, it gets really messy when you use mousehover/mouseenter for such things. I’d prefer using a click event after the first hover or something, this way the user won’t get annoyed by all that movement.

jQuery(document).ready(function() {
    $('#accordion ul:first-child > li').hover(function() {
        $(this).children("ul").slideToggle('slow');
    });

    $('#accordion ul:not(:first-child) > li').click(function(){
        $(this).children("ul").slideToggle('slow');
    });
});

Answer by Starx

I tried to fiddle in your fiddle, but the markup and css are a lot confusing.

As Rikudo said, you should make the div, its child its much easier to do it that way. I have created a simplest accordion skeleton. You can see it here.

It does everything you want. However for the customizations and others things, I will leave it up to you.

Changing background onchange on check box: jquery

Question by danny

I am new to jquery and i am having problem i want to change background color of parent div when i click at checkbox

Please Advice

Thank You

<script type="text/javascript">
    function chngbg(id){
        id2 = "d-" + id;
        $(id2).addClass('bg');
    }
</script>

<div class="dataDiv" id="d-<?=$row->id?>">
    <input type="checkbox" onchange="chngbg($(this).val());" value="<?=$row->id?>" name="cbox" /></span>
</div>

Answer by gilly3

You are missing the # in your id selector.

function chngbg (id) { 
    id2 = "#d-" + id; 
    $(id2).addClass('bg'); 
}

By the way, you’ve got an extra </span> that seems like it doesn’t belong.

Answer by Starx

If you are leaning jquery, its better to do such tasks using the following method.

$("#yourcheckboxselector").change(function() {
    id = "#d-" + id;
    $(id).addClass('bg');
});
September 13, 2011

is it possible to have multiple classes inside php extension?

Question by sunset

I would like to wrapp a .cc code that contains multiple public classes. Is it possible to do that ? how? Do I need to use multiple .cc files one for each class that i want to wrapp?

THX

Answer by Chris

You want to call a C++ class from php? This is incredibly difficult. Usually you have to write a php module (a lot of work). Alternatively you could take a look at Thrift which would let you call your C++ code as a network service (sounds hard, but trust me it’s easier than writing a php module).

Answer by Starx

I wonder what you are attempting to do… if motives were mentioned may be we can help better. Anyways….

To execute a compiled application you can use execute();

$output = exec('/path/to/your/app');

Besides that, you can always write your own php extension….

Check out these tutorials

AFAIK, Many developers use PHP to execute C functions, because it boosts performance quite remarkably.

...

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