...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 24, 2013

Javascript tooltip only appears on second hover

Ghostmancer’s Question:

I am using jQuery and Twitter Bootstrap, and want to have a tooltip appear when hovering over a link. However, the tooltip doesn’t appear the first time I hover over a link, but if I move the mouse away and back on, it works every time for that link.

I have several of these on the page:

<a href="#" onmouseover="$(this).tooltip();" class="postAuthor" data-original-title="@username">Full Name</a>

I’ve created a jsFiddle to demonstrate: jsFiddle. Any help would be appreciated – thanks in advance!

.tooltip() functions initiates the tooltip effect on the link, not show the tooltip

Explanation:

When the $(this).tooltip() is triggered on the first hover, it instantiate the plugin first. Then finally on the second hover you get the tooltip.

Solution:

Add this on your code:

$(function() {
    $("a").tooltip();
});

Solution

Read more

Converting a stand alone java file to a file that's part of a project package?

Sam Peterson’s Question:

I still don’t fully understand where I’m required to use the “public static void main(String[] args)” header within the .java files of a project. Do you need to put that header in every .java file of a package?

I have been following along with chapter 3 in my book, dragging and dropping downloaded stand alone book source files into my project’s package, but some of the .java files in my package don’t like that “public static void main(String[] args)” statement, even though my opening and closing curly braces are in the correct place. Here’s an example of one of those files (the ERROR(S) are described in the code’s comments):

    public class Rectangle
{
   public static void main(String[] args){
   private double length;//ERROR: illegal start of expression
   private double width;

   /**
    * Constructor
    */

   public Rectangle(double len, double w)
   {
      length = len;
      width = w;
   }

   /**
    * The setLength method accepts an argument
    * that is stored in the length field. 
    */

   public void setLength(double len)
   {
      length = len;
   }

   /**
    * The setWidth method accepts an argument
    * that is stored in the width field.
    */

   public void setWidth(double w)
   {
      width = w;
   }

   /**
    * The set method accepts two arguments
    * that are stored in the length and width
    * fields.
    */

   public void set(double len, double w)
   {
      length = len;
      width = w;
   }

   /**
    * The getLength method returns the value
    * stored in the length field.
    */

   public double getLength()
   {
      return length;
   }

   /**
    * The getWidth method returns the value
    * stored in the width field.
    */

   public double getWidth()
   {
      return width;
   }

   /**
    * The getArea method returns the value of the
    * length field times the width field.
    */

   public double getArea()
   {
      return length * width;
   }

}//end of: public static void main(String[] args)

}//end of: public class Rectangle  ERROR: class, interface, or enum expected

The ERROR(S) came up after I added the “public static void main(String[] args)” to the existing Rectangle.java file. Any idea of why this occurs?

This occurs because You cannot have more than one main() method in a package. However overriding the main method is definitely allowed. What I mean is as, long the parameter number is differed you can override main() method.

public static void main(String[] args) {
   .....
}

And somewhere else in other or same class, you can add such class

public static void main(String arg1, String arg2) {
    .....
}

The ERROR: illegal start of expression is because you are using access modifier inside the method. Use all the access mofifier and variable declaration inside the class

public class Rectangle {

    private double length;//ERROR: illegal start of expression   
    private double width;

    public static void main(String[] args) {
    ....
    }
}

The ERROR: class, interface, or enum expected is because the class Rectangle is only housing a static method, your all the methods and parameters are inside the static method called main()

Here is your code which will compile without an error.

Read more
June 20, 2013

addClass vs attr and creating an ID

Aaron’s Question:

So what I am reading is that when adding a class to an element without any class selectors, use the addClass() method over attr().

For example, using:

.addClass('myclass')

is more efficient than

.attr('class','myclass')

I cannot find anything equivalent to addId(‘myid’) for adding id selectors, does it exist or is attr() the best way to add an id selector?

I get that id is unique, the logic behind my question is addClass() is faster than attr().

So my question is if there’s a more efficient method for creating an id than attr().

Answering directly

No, addId() does not exist and addClass() is not as same as attr()

In HTML, a class attribute can hold more than one value like <div class="tall fat brown">Someone</div> so jQuery’s function addClass() helps to add a value to the class attribute not change it. Similarly the functions toggleClass() and ‘removeClass()` help manipulate them.

But the function attr() will just manipulate the attribute and change it directly.

For example:

<div id="person">someone</div>

And the following jQuery Statements

$("#div").addClass("tall"); // This will create the class attribute and add tall 
$("#div").addClass("fat");  // This will append fat to the existing class and make "tall fat"
$("#div").addClass("brown"); // likewise

.addClass() will just append the class name. If same needs to done by using attr() you have to do

$("#div").attr('class', 'tall');
$("#div").attr('class', 'tall fat');
$("#div").attr('class', 'tall fat brown');

Or, you can modify the attribute using

$("#div").attr('class', function(i, className) {
    return className + " brown";
});

Where as ids have one value that needs to be modified or altered so a function like addId() would do exactly which attr(‘id’, ‘idvalue’) would do.

Read more

Adding div from JSON in jQuery?

Ted’s Question:

I am getting some data from a page in JSON format
JSON:
{
‘name’ : ‘maverick’,
Image : ‘Jason’
}

I now need to take these values and add them to the #main div.

        <div id="main">
        <div class="a"> name: Eithan <img src="img/Eithan.jpg" /> <div>
        <div class="a"> name: Emma <img src="img/Emma.jpg" /> <div>
       </div>

How do I do that in jQuery for the case there are several objects in the JSON?

You can do this by using $.getJSON() function.

$.getJSON("link/to/json", function(data) {
    $.each(data, function(i, item) {
        $('#main').append('<div class="a"> name: ' + item.name + ' <img src="img/' + item.image + '.jpg" /></div>');
    });
});
Read more

php variable assignment confusion

Robert Rocha’s Question:

While reading a book about php I cam across a piece of code that logically doesn’t make sense to me. The line of code is part of a class function:

private function replaceTags( $pp = false ) {
    //get the tags in the page
    if( $pp == false ) {
        $tags = $this->page->getTags();
    } else {
        $tags = $this->page->getPPTags();
    }
    //go through them all
    foreach( $tags as $tag => $data ) {
        //if the tag is an array, then we need to do more than a simple find and replace!
        if( is_array( $data ) ) {
            if( $data[0] == 'SQL' ) {
                //it is a cached query...replace tags from the database
                $this->replaceDBTags( $tag, $data[1] );
            } elseif( $data[0] == 'DATA' ) {
                //it is some cahched data...replace tags from cached data
                $this->replaceTags( $tag, $data[1] );
            }
        } else {
            //replace the content
            $newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );
            $this->page->setContent( $newContent );
        }
    }
}

The specific line that doesn’t make sense to me is:

$newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );

How can you pass the variable “$newContent” to “setContent( $newContent )” when it doesn’t have a value yet?

Any explanations?

That statement is executing in a for loop so, $newContent will hold the value in another loop to use.

In the first execution, $newContent will be empty but on the next iteration it will have a value to replace.

foreach( $tags as $tag => $data ) {
    if ....
    } else {
        //replace the content
        $newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );
     // ^
     // Now next time when the loop executes again it will have a 
     // $newContent to process.

        $this->page->setContent( $newContent );
    }
}
Read more

Access an internally used list

Pulz’s Question:

I’m coding the Dijkstra algorithm in Java. My first method

public void populateDijkstraFrom(Node startNode)

creates a Linked List of nodes with its respective distances and predecessors. My second method

public List<Node> getShortestPath(Node startNode, Node targetNode)

is supposed to create a list of nodes with the shortest path from the startNode to the targetNode using the list of nodes from my populateDijkstraFrom method.

However, I don’t know how to access the list of nodes from my Dijkstra method in the getShortestPath method. I could change the return type from void to LinkedList but I was told that it works using void.

How do I do it?

Thanks

There are basically two ways of solving this.

Easiest one would be return the list of nodes on your method

public List<Node> populateDijkstraFrom(Node startNode) {
       // ^ Configure to return list instead of void

    // ......
    return nodeList;
}

public List<Node> getShortestPath(Node startNode, Node targetNode) {
    List<Node> pdList = populateDijkstraFrom(startNode);
    // ^ --- Get the list by simply passing the same parameter to the method
}

Another is stated by Gian

Read more
June 19, 2013

How to check if there aren't any result after querying and execute another statement?

K20GH’s Question:

I’m trying to do something fairly simple as per below. Basically, I want to check to see if a user exists using their ‘gid’. If they don’t exist, add them to the database, if they do, echo “User Already Exists”

For whatever reason, it will always add a new user, even if their gid exists.

$checkuser = "SELECT gid FROM user WHERE gid = '$id'";
$adduser = "INSERT INTO user (gid, name, pic) VALUES ('$id','$name','$img')";

if (!mysql_num_rows($checkuser))
{
    if (!mysqli_query($con,$adduser))
      {
      die('Error:  ' . mysqli_error($con));
      }
    echo "1 record added";
}
else {
    echo "User Already Exists";
    }

There is many things wrong with your code. First and the most important is you have a query a statement, if you do not query, you will not receive any result-set and the resultant is new registration every time.

Function is_resource() will help you decide whether or not the query
returns valid result.

Add here is the correct way to solve your problem.

$checkuser = "SELECT gid FROM user WHERE gid = '$id'";
$adduser = "INSERT INTO user (gid, name, pic) VALUES ('$id','$name','$img')";

$result = mysqli_query($con, $checkuser)); 
          // ^-- You have to query first to find out if there are any users or not

if(is_resource($result) && mysqli_num_rows($result) > 0) {
   // ^ This will confirm the query has returned a result and it contains rows

     echo "User Exists";
} else {
   // If it does not you can finally add it

     $result = mysqli_query($con, $adduser) or die(mysqli_error());
     echo "User added"; 
}
Read more
June 18, 2013

Disable direct access to files in PHP

Mr Me’s Question:

I’ve already checked the issue disable access to included files , but I am wondering if that’s the best solution.

Context: I’m building a bootstrap class for my PHP Framework, and realized that there are multiple solutions to this security issue.

After researching and reading posts like the one I mentioned at first and others related to htaccess, I think that there are basically three types of solutions:

1 – Checking a constant (like in the post I linked)

if(!defined('THIS_IS_NOT_A_DIRECT_ACCESS')) {
    header('HTTP/1.1 404 Not Found');
    include('./../error/404.php');
    die;
}

Or

require('../error/include_file.php');
//
if(!defined('THIS_IS_NOT_A_DIRECT_ACCESS'))
{
    header('HTTP/1.1 404 Not Found');
    include('404.php');  
    die; 
}

2 – Redirecting all calls to the Bootstrap and making a clever filtering.

//Something like
// if $urlRequested it's a file
    // Go to Error
// else if $urlRequested it's not a controller
    // Go to Error
// else 
    // Execute Controller Logic.

3 – Setting htaccess.

# Redirecting calls for non-directories, files or links
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA]

# Redirecting the rest of the calls to the error page.
RewriteRule ^(.+)$ index.php?url=error/404 [QSA]

Personally I think the solution 3 is the most interesting, but I am pretty new in the Htaccess control so I wonder if this is a safe solution.

For the purists and minimalists, the Question in here would be:
Are these (the three examples) nice direct access control systems for Apache-PHP applications? Else, which would be the safest approach? And the simplest?

This is a debatable topic but .htaccess rules applies to all the document on that particular directory. While applying 1 or 2 you may have to include that portion on every file.

Read more

Selecting more than one option

User2386255’s Question:

I have the following code working pretty well, but I want to be able to select more than one option if need be: http://jsfiddle.net/exlondoner/MKa3n/

Can anyone help?

JS:

$('.media-select-option').on('click', function() {
    $('.media-select-option').removeClass('selected');
    $(this).addClass('selected');     
    $('.m-overlay-close-btn').addClass('checked');       
});

Try this:

$('.media-select-option').on('click', function () {
    $(this).toggleClass('selected');
    $('.m-overlay-close-btn').addClass('checked');
});

FIDDLE

It is not working because there is no such element with class m-overlay-close-btn

$('.overlay-close-btn').addClass('checked');

Working fiddle

Read more

Dropdown Menu CSS

Wizzme’s Question:

I cannot figure out what is wrong with my dropdown menu. When I over over the main level link, the drop down appear but at the left of my screen instead of underneath the main link.
I have been on this for a couple of hours and any help would be greatly appreciated.

Here is the html part :

<div class="nav">

        <ul id="menu">
           <li><a href="#" class="current">Home</a></li>
              <li><a href="#">Apetiziers</a>
              <ul>
               <li><a href="#">Sub-Link 1</a></li>
               <li><a href="#">Sub-Link 2</a></li>
               <li><a href="#">Sub-Link 3</a></li>
               <li><a href="#">Sub-Link 4</a></li>
              </ul>
              </li>

              <li><a href="#">Entree</a>
             <ul>
             <li><a href="#">Sub-Link 1</a></li>
             <li><a href="#">Sub-Link 2</a></li>
             <li><a href="#">Sub-Link 3</a></li>
             <li><a href="#">Sub-Link 4</a></li>
             </ul>
              </li>

              <li><a href="#">Main Course</a>
             <ul>
             <li><a href="#">Sub-Link 1</a></li>
             <li><a href="#">Sub-Link 2</a></li>
             <li><a href="#">Sub-Link 3</a></li>
             <li><a href="#">Sub-Link 4</a></li>
             </ul>      
              </li>

              <li><a href="#">Dessert</a>
             <ul>
              <li><a href="#">Sub-Link 1</a></li>
              <li><a href="#">Sub-Link 2</a></li>
              <li><a href="#">Sub-Link 3</a></li>
              <li><a href="#">Sub-Link 4</a></li>
             </ul>      
              </li>


              <li><a href="#">Contact Us</a></li>
        </ul>

 </div>

And the .css :

ul#menu {
   float: left;
  margin: 0;
  width: auto;
    padding: 0px 40px 0px;
    background: #333; color: #fff;
    line-height: 100%;
}

ul#menu li {
  display: inline; 
}


/* top level link */
ul#menu a {
  float: left;
  padding: 10px 16px;
  margin-right: 0px;
  background: #789; color: #fff;
  text-decoration: none;
  border-right: 1px solid #e2e2e2;
}

/* main level link hover */
ul#menu a.current {
  background: #f60; color: #fff;
}


ul#menu li:hover > a {
  color: #fff; background: #ff4500;
  text-decoration: underline;
}

/* dropdown */
ul#menu li:hover > ul {
    display: block; /* shows the sub-menu (child ul of li) on hover */
}

/* sub level list */
ul#menu ul {
    display: none; /* hides the sub-menu until you hover over it */
    margin: 0;
    padding: 0;
    width: 140px;
    position: absolute;
    top: 35px;
    left: 0;
    background: #000;
    border: solid 1px #ccc;
}

ul#menu ul li {
    float: none;
    margin: 0;
    padding: 0;
}

ul#menu ul a {
    font-weight: normal;
    background: #9BB3BF; color: #036;
}

/* sub levels link hover */
ul#menu ul li a:hover {
color: #036; background: #DDDF99;
}

It is probably jumping towards the closest relative container. So configure your list to act as relative container:

ul#menu > li {
  position: relative;
}

Also there was unnecessary float in your anchor tags, your li are already set to display as inline there is no point in float them

ul#menu a {
    display: inline-block;
    padding: 10px 16px;
    /* ... */
}

Here your fixed code

Read more
...

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