...

Hi! I’m Starx

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

Get bottom and right position of an element

Question by Cameron

I’m trying to get the position of an element within the window like so:

var link = $(element);

var offset = link.offset();
var top = offset.top;
var left = offset.left;
var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;
var right = $(window).width() - link.width();
right = offset.left - right;

However the bottom and right have - in front of them… Why is this? as the numbers are correct just they should NOT be minus.

Answer by Mordhak

Instead of

var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;

Why not doing

var bottom = $(window).height() - top - link.height();

Edit : your mistake is to do

bottom = offset.top - bottom;

instead of

bottom = bottom - offset.top; // or bottom -= offset.top

Answer by Starx

You can use the .position() for this

var link = $(element);
var position = link.position(); //cache the position
var right = window.width() - position.left - link.width();
var bottom = windows.height() - position.right - link.height();
Read more

Check if AJAX loaded form contain a submit button

Question by Merianos Nikos

Is there a way to check if the form that has been loaded with AJAX contain a submit button with jQuery ?

Answer by Darin Dimitrov

success: function(content) {
    $('#someplaceholder').html(content);
    var containsSubmitButton = $(':submit', content).length > 0;
}

Answer by Starx

You can do it as this

$("#div").load("yourpage", function() {
    if($("#div").find(":submit").length > 0) {
          console.log("yes");
    }
});
Read more

Can we add images into outlook mail using php?

Question by harismahesh

I have a Create task page. So once Task is created, and if user admin clicks mail button. Outlook will open and add the subject and body which I typed.

But my doubt is can I add an image and also can we change teh font color in Message using code itself. I am a newbie in this thats why the dumb doubt.

<a href="mailto:xxxx@xxxx.com?subject=Any Subject&body= Any Topics">Mail</a>>

Answer by Starx

Outlook is just an email application, which shows email as it appears.

There is no such thing as Outlook Compatible email.

You should provide direct link to images where you are sending a HTML email. Here is simple example of doing this using native mail()[docs] function.

<?php
$subject = 'Email with image';
$message = '
    <html>
    <head>
      <title>Email with image</title>
    </head>
    <body>
      <p><img src="http://mydomain.com/direct/link/toimage.jpg" /></p>
    </body>
    </html>';

$headers  = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";

// Additional headers
//..................

mail($to, $subject, $message, $headers);
Read more

insert image at span position

Question by clankill3r

I have 2 rows, the first has all the text and the second will hold the footnotes and additional images.

In the text row i want to show a small image to alert the reader that there is a footnote.
I want to do this with jquery, i try to get the original position but it doesn’t work.
I think because i try to get the position of the class instant of the span.
But i don’t know how to get it of the span (with the class b_footnote!).

$('#container #book #column1 .b_footnote').each(function(){
    console.log($(this)); // goes good
    console.log($(this).position.left); // undefined
});

here’s some example html

<p>
en Benkei nog rust vonden. In een vertrek was Yoshitsune met zijn vrouw en jeugdig kind. De Dood stond in het vertrek gereed, en het was beter, dat de Dood zou komen op bevel van Yoshitsune, dan op bevel van den vijand buiten de deur. Zijn kind werd door een bediende gedood, en terwijl hij het hoofd van zijn geliefde vrouw onder den linkerarm nam, stootte hij zijn zwaard diep in haar nek. Na dit te hebben volbracht, pleegde Yoshitsune zelfmoord (hara-kiri).<span class="b_footnote">De buik opensnijden.</span> Benkei echter wachtte den vijand op. Hij stond met zijn groote beenen wijd uitgespreid, zijn rug tegen een rots gedrukt. Toen de dageraad aanbrak, stond hij nog altijd met uitgespreide beenen, terwijl zijn dapper lichaam door duizend pijlen was doorboord. Benkei was dood, maar vallen kon de krachtige held niet. De zon verrees over een man, die een ware held was, en die steeds getrouw was gebleven aan de eenmaal door hem uitgesproken woorden: “Waar mijn meester heengaat, hetzij ter overwinning, of in den dood, ik zal hem volgen.”</p>

I get it to the second row like this:
I don’t know if that will cause problems with showing the hint image on the original spot in the text.

.b_footnote {
    background: yellow;
    position: absolute;
    left: 540px;
    z-index: 99;
}

other solutions are welcome as well.

Answer by Starx

To get the CSS position as you defined, you should use

$(this).css('position');

To insert image after the span position, you can use jQuery’s .after()[docs]

$("span").after('<img src="link/to/image.jpg" />'); //Select the span and insert the image
Read more

obtaining querystring from current url in javascript?

Question by AbdulAziz

I have a example URL: http://localhost/PMApp/temp.htm?ProjectID=462 And i have to get the details after the “?” sign that is “ProjectID=462”. I want to do it in JavaScript.

I done this so far and not getting idea what to do next:

var url = window.location.toString();
url.match(?);

Can some body help.Thanks

Answer by Christofer Eliasson

Have a look at the MDN article about window.location.

The QueryString is available in window.location.search.

MDN also provide an example of how to the get value of a single key available in window.location.search.

Something like this:

function loadPageVar (sVar) {  
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\?]" + escape(sVar).replace(/[.+*]/g, "\$&") + "(?:\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would alert the value of QueryString-variable called name  
alert(loadPageVar("name")); 

Answer by Starx

Use window.location.search to get everything after ? including ?

Example:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
Read more

How can i do button on hold for two second call function1 if less then two second call function2?

Question by YumYumYum

I have this button which is not working correctly for hold button for a period (but it works like click only).

Where i was trying to do if the button is hold for greater/equal then 2 seconds then callfunction1, if the button was pressed less then 2 seconds then callfuntion2.

var clickDisabled = false;

function clickLocker() {      
  /* @Button: 2 seconds */
  clickDisabled = true;
  setTimeout(function(){clickDisabled = false;}, 2000);      
}

function callfunction1() { // you have hold he button for greater then or equal 2 second } 
function callfunction2() { // you have hold the button less then 2 second } 

$('.button').live("click",function()
{ 
  if (clickDisabled) {
    alert("locked for 2 second");
    return;
  }
  clickLocker();
});

Answer by Starx

That was a great suggestion from slash. This is how you can do this

var clickstart;
var clickstop;
$("a").on('mousedown', function(e) {    
    clickstart = e.timeStamp;
}).on('mouseup', function(e) {
    clickstop = e.timeStamp- clickstart
    if(clickstop >= 2000) two()
    else one();
});

Demo


Updates:

It might be necessary to track the mouse movement like @MarkRhodes wrote in his comments. So for that, check this update

Read more

Editing a row of data in a table using an id

Question by Tesh

I am stuck with finding a means of being able to edit a specific row in my table. I have so far managed to come up with add,delete and search for a specific item that is stored in my database, i base the delete on a id field. Currently i am using PHP and HTML, could someone please show me a simple example that retrieves data from a database which stores in a table and when a user selects edit. The row that has been selected for edit becomes editable and thereafter updated without duplicating the data.

CLARIFICATION OF My QUESTION

For Editing to work the UI must look like, when the edit button corresponding to particular row is clicked then all the columns with the data should get replaced with text boxes, i.e. row-wise edit form…

Thanks

Answer by Starx

This is a very vague question, involves a lot of things. Not, just php, mysql or html but mainly javascript. However I will give a simple example, since you must already be able to bring the data onto a table.

Suppose your <tr> structure is similar to this

<tr>
<td class="nameField"><span class="text">My name</span></td>
<td class="controls"><a class="edit">Edit</a></td>
</tr>

Now using jQuery for this

$('a.edit').click(function() {
    $(this).closest("tr").find("td").not(".controls").each(function(k,v) {
                       // ^ find all td but not the one with the controls
        var span = $(this).children('span');
        //get the elem holding the value

        $(this).append('<input type="text" value="'+span.text()+'" />');
        // Add a text box with the input inside the td
        span.hide();
    });
});

Demo

Read more

Mysql, functions for tree-structure

Question by user809829

I have a tabel containing a column named parent which is able to store a parent ID.
This makes it possible to create a tree-structure of my data.

Are there any good helper-functions for travelling through such a tree-structure in MySQL?

For example, if I have a row in my table and I want to be able to retreive all “parents” above it. So getting the it’s parent’s parent ID and so on…

Answer by cctan

Copied from this popular link:

CREATE TABLE nested_category (
        category_id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(20) NOT NULL,
        lft INT NOT NULL,
        rgt INT NOT NULL
);

INSERT INTO nested_category VALUES(1,'ELECTRONICS',1,20),(2,'TELEVISIONS',2,9),(3,'TUBE',3,4),
 (4,'LCD',5,6),(5,'PLASMA',7,8),(6,'PORTABLE ELECTRONICS',10,19),(7,'MP3 PLAYERS',11,14),(8,'FLASH',12,13),
 (9,'CD PLAYERS',15,16),(10,'2 WAY RADIOS',17,18);

SELECT * FROM nested_category ORDER BY category_id;

+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          |   1 |  20 |
|           2 | TELEVISIONS          |   2 |   9 |
|           3 | TUBE                 |   3 |   4 |
|           4 | LCD                  |   5 |   6 |
|           5 | PLASMA               |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |  10 |  19 |
|           7 | MP3 PLAYERS          |  11 |  14 |
|           8 | FLASH                |  12 |  13 |
|           9 | CD PLAYERS           |  15 |  16 |
|          10 | 2 WAY RADIOS         |  17 |  18 |
+-------------+----------------------+-----+-----+

You can use this to find all parents from node FLASH:

tree
Retrieving a Single Path

With the nested set model, we can retrieve a single path without
having multiple self-joins:

SELECT parent.name
FROM nested_category AS node,
        nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND node.name = 'FLASH'
ORDER BY node.lft;

+----------------------+
| name                 |
+----------------------+
| ELECTRONICS          |
| PORTABLE ELECTRONICS |
| MP3 PLAYERS          |
| FLASH                |
+----------------------+

This works because the child’s left will be in between its parents’ left and right.
You can read further or search for modified preorder tree traversal.

Answer by Starx

Please read this “Hierarchical queries in MySQL” article, for in depth explanation on the topic.

But still I would like to keep things simple and create a recursive PHP function instead.

But after reading few articles, I found that best way regarded for this, is Modified Preorder Tree Traversal, which has been further explained in this article.

Read more

Which performs better in MySQL?

Question by johnnietheblack

I would like to update 3 rows of a single table, with different values each.

The way I see it I could either…

Option 1.
Simply create a PHP loop, and run a query for each row I’d like to update. (this is the ‘classic’ approach, maybe).

Option 2.
Follow the approach of combining into a single query, but that uses syntax that I have heard is slower, depending on the situation. (example copied from: this website):

UPDATE mytable
SET myfield = CASE other_field
    WHEN 1 THEN 'value'
    WHEN 2 THEN 'value'
    WHEN 3 THEN 'value'
END WHERE id IN (1,2,3)

Which is a better, faster option?

Answer by Daan

I’m almost certain the single MySQL query will be slower than separate UPDATE queries, but you could always try. If immediate consistency is not a concern, you could also consider using individual UPDATE LOW_PRIORITY queries which should be even faster still.

The best way to know what works for your application, as always in programming, is to benchmark the performance of both queries and experiment a bit 🙂

Answer by Starx

Single query will be far more faster than querying the server multiple times in a loop.

So, second way is the way to go.

Read more

How to get the rendered PHP+HTML codes into a text file?

Question by Leo Chan

I have a file which is combination of PHP and HTML.

How can i get the plain HTML code output from this file into a text file? or either put it into the text box.

The code of my form, which i use to generate an HTML form can be found here

Answer by Starx

Update:

It seems OP is asking about HOW to get the rendered PHP+HTML codes into a text file?

//get the output from the file
ob_start();
include "yourphpplushtml.php";
$output = ob_get_clean();

//now create a text file and write to it
$fp = fopen('data.txt', 'w+');
fwrite($fp, $output); //put the output
fclose($fp); //close the handler

//Or put it into the textare

echo '<textarea>'.$output.'</textarea>';

Previous Answer But may be helpful to others too

There are many ways HTML can be combined with PHP

  1. Output HTML directly from PHP

    <?php
       echo "<head><title>my new title</title></head>";
    ?>
    
  2. Include PHP inside you HTML

    <title><?php echo $dynamictitle; ?></title>
    
  3. Or even separate them in old fashioned complicated way

    <?php if($resultFound == true) { ?>
        <p> The result was successfully found.</p>
    <?php } ?>
    
Read more
...

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