...

Hi! I’m Starx

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

Tinymce – Is it possible to get caret position of textarea corresponding to WYSIWYG Editor?

Question by user1643156

I’m wondering if we can get the real caret position of textarea when the fake cursor is in certain position under WYSIWYG Editor?

To better understand the question, please see the image below

enter image description here
Under WYSIWYG mode, when the cursor is after s, we get position 53. and when the cursor is after t, we get position 79.

The code would be something like…

function getRealCaretPosition() {
    // all the dirty work goes here
}

// Ctrl + Q
if(e.ctrlKey && e.which == 81) {
    var pos = getRealCaretPosition();
    alert(pos);
}

Is this possible to be achieved, in theory?

Answer by Starx

Yes, there is a topic covered on tinyMCE illustrating this:

var inst = getInstanceById('editor/elementid');
var myBookmark = inst.getBookmark();

// do something, move the cursor position
inst.moveToBookmark(myBookmark);

Source: Check other solution from here, if these dont work.

Read more

set php session variable using ajax/jquery

Question by user2102316

Im new to ajax/jquery. so is there an easy way that when i click a cell with in the table, the value of it will be stored in a session variable.

thanks in advance

Answer by Starx

It can be as simple as this:

The following snippet send the value to a page where session variable can be set

$.post('sessionsetter.php', { 'fieldname' : 'sessionvariablename', 'value' : 'sessionvalue'});

Now ‘sessionsetter.php’ can be something like this:

session_start();
$_SESSION[$_POST['fieldname']] = $_POST['value'];

Now, you can send as many variables you want to set as SESSION variable.

Read more

How do I structure a bunch of items that chain together in a MySQL database?

Question by HartleySan

I apologize for the vagueness of my question title, but I don’t even know what to call what I’m trying to accomplish.

The best way to describe what I want is that I want to be able to chain a bunch of items together, and then (possibly) recursively find all the items that are part of any chains that contain the target item. For example, note item3 in the following chains:

item1 => item2 => item3 => item4
item5 => item3 => item6  
item3 => item7 => item8  
item3 => item9 => item10  
item11 => item12 => item13 => item3

If a user were to do a search for item3, then I’d want all five chains above to be displayed. In other words, I want to be able to find all descendants and ancestors of item3, so that I can display the data in an HTML table (or whatever HTML structure works best).
The thing that makes this tricky is that (as shown above) any given item may have many descendants and many ancestors. As such, I’m not sure that regular recursion in MySQL would work.
I did have a look at both of the articles linked to in the top answer for the following SO thread, but I don’t think that the suggested solutions will work for my desired data structure:
Mysql recursion?

Is there any way to structure this kind of data into a MySQL DB so that with fairly easy and lightweight queries (i.e., hopefully one query per item request), I can get the information and structure I’m looking for?
Thank you very much.

Answer by Starx

I have a suggestion.

Store item in the following structure.

+---------+-----------+
|   id    |    item   |
+---------+-----------+
|   1     |   item3   |
+---------+-----------+

And add the link references in the following

+---------+-----------+------------+
|  itemid |  ancestor | descendant |
+---------+-----------+------------+
|  1      |  3        | 2          |
+---------+-----------+------------+
|  1      |  5        | 7          |
+---------+-----------+------------+

Create a index on all three columns. This will enable you to add same time as many times as it appears on a chain.
Also you can query a particular item to find all its related links.

Read more

POST variable is not being saved correctly

Question by user2078757

Im using method post to send a mutliple input text form, i draw information from the database to after re insert the information which is inside input text:

echo "<CENTER><TABLE BORDER='0'>";
echo "<FORM METHOD='POST'>";
$sele_players = "SELECT nombre FROM JUGADORES WHERE NOM_EQUIPO='Aston villa'";
        $sele_players = mysql_query( $sele_players , $link );

        while( $row = @mysql_fetch_assoc( $sele_players ) )
        {
            $row['nombre'] = addslashes( $row['nombre'] );
            echo "<TR><TD ALIGN='CENTER'>".$row['nombre']."</TD>";
            echo "<TD><INPUT TYPE='TEXT' NAME='{$row['nombre']}'></TD></TR>";
        }

        echo "<TR><TD COLSPAN='2' ALIGN='CENTER'><INPUT TYPE='submit' NAME='send2' VALUE='INSERTAR' style='width:200px; height:60px' ></TD></CENTER></TR>";

ok here i get the names of players from database, then i use them for insert inside input text as his name, to after pick with array $_POST:

    if( !empty( $_POST['send2'] ) )
    {

        foreach($_POST as $jugador => $points)
        {
            $jugador = str_replace( "__" ,". ", $jugador );
            $jugador = str_replace( "_" ," ", $jugador );

            if( $points == "" )
            {
                $points = "NULL";
            }

            $inser_jornada = "INSERT INTO JORNADA VALUES( '{$_GET['jornada']}','{$_GET['equipo']}', '$jugador', '$points', now() );";

So there is no problem with most of names, excluding N’Zogbia name or apostrophe names which is shown in $_POST array as ‘N’, i have tried adding slashes before send it through from but doesnt work, so i dont know how to get the complete name in post array, thats the main problem.

THanks forwarded!!

Answer by Starx

There are many things to point out here. But instead of that, I will try my best to be helpful.

Add your database entries using mysql_real_escape_string($variableName) to enter the content to the database. It will automatically escape such quotes and make it a little SQL Injection proof.

Read more
February 22, 2013

How to identify if javascript is diabled by browser

Question by Umesh

I was puzzled with a question. Many browsers like Internet Explorer allows to disable the javascript.

How do I check through whether the user’s Browser has disabled javascript or not?

Answer by Starx

In addition to pdeurstler’s answer, there is an old school way.

It is tad old school but, <noscript>...</noscript> detects JavaScript being disabled and executes the embed HTML.

Read more

When clicked insert text into ul li

Question by user1847112

I’m new to javascript/jquery and could need some help. When I click on the test button a new ul containing an li is appended into the body with the value of the input field. When clicked on the li element it should be removed. If there is nothing inside the ul, it should be also removed.
How can I make the code to create unordered list once and then insert li‘s inside? Also, how should I proceed to remove a li when I click on them?

This is the code I have now:

<input type="text" value="" id="text" />
<input type="button" id="test" value="Test" />
$(document).ready(function(){
    $("#test").click(function(){
        var t = document.getElementById("text").value;
        var UL = document.createElement('ul')
        var LI = document.createElement('li')
        $(UL).attr('id','main-list').appendTo(body)
        $(LI).appendTo("#main-list").text(t)
    });
    $("ul#main-list li").click(function(){
        $(this).remove()
    });
});

Answer by Starx

Just a small change is enough:

$("body").on("ul#main-list li", 'click', function(){
    $(this).remove()
});
Read more
February 18, 2013

Align width of container div to the sum of floating div

Question by Seb37

I have the following html:

<div class="main_container">
    <div class="sub_container">
        <div class="floating">wookie1</div>
        ...
        <div class="floating">wookie5</div>
    </div>
</div>

I want sub_container to have the exact width of the sum of the floating div.

If I use “display:table;” for sub_container and “display: inline-block;” for floating divs, it works fine:

enter image description here

until I have enough div in the list, so that the sum of width is larger than main_container and they break on the next line:

enter image description here

But still, I want subcontainer (yellow background) to to be ALWAYS the EXACT WIDTH of the sum of the divs, even when they go on several lines, like this:

enter image description here

I’ve googled for hours now, and wasn’t able to find an elegant solution (css only, if possible.)

Here’s the jsfiddle, to play with this.

Answer by Starx

I got bored trying this and created a JS script based on jQuery to solve it.

var t = $(".sub_container").width()/$(".floating").outerWidth();
$(".sub_container").width(parseInt(t) * $(".floating").outerWidth());

Demo

Read more
February 4, 2013

Inline-block, Inline, Block

Question by Zettam

I’ve been searching about CSS lately, trying to teach myself the tricks.
One another issue I’ve encountered is directly related to the display: attribute.

I’ve been trying to get the width of the background element for my “menu buttons” as wide as the text they contain. The buttons are simply <div> elements.

When I use display:block; all of their width appear as wide as the longest item, and when I set it to display:inline; or display:inline-block they simply appear on the same line, just like how an inline element works.

Now, what I’m wondering is, how can I make them appear like a list, but still make the background color only as long as the text it contains?

Answer by Starx

Use a markup structure like this

<ul id="menu">
<!-- By the use of UL you can have the menu displayed as list -->
    <li><a href="#">Home</a></li>
    ...
</ul>

And apply the background CSS on the #menu li a

#menu li a {
    /* a (anchor tag) is an inline tag, so the background 
    will span up to its content only */

    background: url("../src/to/img.jpg");
}
Read more
January 20, 2013

how to determine whether string is a valid html4 tagName?

Question by cc young

given a string, ‘div’ or ‘abc’, is there any way to determine whether the string is a valid html4 tagName?

tried using document.createElement(), but it’s happy with anything:

document.createElement('trash')
=> <trash></trash>

cannot use HTML<tag>Element. for example

document.createElement('tbody')
=> HTMLTableSelectorElement

Answer by minitech

The best way is to have a list of all valid HTML4 elements and check that. This will give you the right result for “a valid HTML4 element” 100% of the time. From here:

var html4 = ["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","B","BASE","BASEFONT","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","DD","DEL","DFN","DIR","DIV","DL","DT","EM","FIELDSET","FONT","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HR","HTML","I","IFRAME","IMG","INPUT","INS","ISINDEX","KBD","LABEL","LEGEND","LI","LINK","MAP","MENU","META","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","P","PARAM","PRE","Q","S","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRIKE","STRONG","STYLE","SUB","SUP","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TITLE","TR","TT","U","UL","VAR"];

var valid = html4.indexOf(name.toUpperCase()) !== -1;

(Or, using an object, as @SLaks suggested.)

If you absolutely don’t want to do that for some reason, or didn’t actually mean HTML4, and aren’t worried about IE8- compatibility, then you can do this:

var valid = !(document.createElement(name) instanceof HTMLUnknownElement);

Answer by Starx

A rather simple technique is to define your own set of valid HTML Elements

Array.prototype.contains = function(k) {
   return (this.indexOf(k) > -1;
}
var ValidTags = ['html', 'head', ....];
//Then compare
if(ValidTags.contains('trash')) {
   //Then its valid
}
Read more

Detect page zoom change with jQuery in Safari

Question by C.O.

I have a problem with Safari in a web application that contains a position:fixed element. When the page is zoomed out (smaller 100%) things break and would need to be fixed by calling a function. So I’d like to detect the user’s zooming. I found this jQueryPlug-in a while ago:

http://mlntn.com/2008/12/11/javascript-jquery-zoom-event-plugin/

http://mlntn.com/demos/jquery-zoom/

It detects keyboard and mouse events that might lead to a page zoom level change. Fair enough. It works on current FF and IE but not on Safari. Any ideas what could be done to do something simmilar in current WebKit browsers?

Thanks.

Answer by newtron

It’s not a direct duplicate of this question since that deals with Mobile Safari, but the same solution will work.

When you zoom in, window.innerWidth is adjusted, but document.documentElement.clientWidth is not, therefore:

var zoom = document.documentElement.clientWidth / window.innerWidth;

Furthermore, you should be able to use the onresize event handler (or jQuery’s .resize()) to check for this:

var zoom = document.documentElement.clientWidth / window.innerWidth;
$(window).resize(function() {
    var zoomNew = document.documentElement.clientWidth / window.innerWidth;
    if (zoom != zoomNew) {
        // zoom has changed
        // adjust your fixed element
        zoom = zoomNew
    }
});

Answer by Starx

There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

window.onresize = function onresize() {
  var r = DetectZoom.ratios();
  zoomLevel.innerHTML =
    "Zoom level: " + r.zoom +
    (r.zoom !== r.devicePxPerCssPx
        ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
        : "");
}

Demo

Read more
...

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