...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page

Positioning an element w.r.t the window using jquery

Question by Vinay

var wdt = document.body.offsetWidth/2.6

var hgt = document.body.offsetHeight/4

$("#element").offset({left:wdt, top:hgt})

what i am trying to do is position the image(#element) relative to the body..ie to the center with respect to the window … for different Browser/window sizes/screen….irrespective of any screen.

Is this valid.. or are there any more..?

Answer by Elliot Bonneville

$("#element").css({left:50%, top:50%});

or

$("#element").css({left:window.innerWidth/2.6, top:window.innerHeight/4});

Should do it. Or better yet, in your CSS file:

#element {
    left:50%;
    top:50%;
}

Be aware that this will position your element based on the upper left corner, so it won’t appear to be in the exact center. To account for that, you could do this (keeping the above CSS):

$("#element").offset({
    left:-$(this).css("width")/2,
    top:-$(this).css("height")/2
});

Answer by Starx

Using jQuery

$("img").css({
  top: ($(window).height()-$("img").height())/2,
  margin: '0 auto'
});
Read more

Jquery (input/textarea).val(): how is it adding content without changing the DOM?

Question by Li Haoyi

take a look at the JsFiddle here:

http://jsfiddle.net/ru2Fg/2/

Essentially, it starts with two textareas: one empty, one with stuff inside, and an input type=text. I was under the impression that to put stuff in an input you change it’s value, and to put stuff in a textarea you add the text as a child to the node.

I perform a $(...).val(...) to change their contents. And their contents do change.

However, the DOM looks exactly the same! I’m printing out the 3 elements with console.log(); they seem unchanged. I look at them with chrome’s inspect element: they seem unchanged.

I’ve looked at jQuery val() change DOM, but that question concludes it’s something funny with firebug not refreshing the HTML it displays. In this case, i’m quite sure inspect element displays the current html that exists on the page: i’ve seen the left attribute changing furiously when things are scrolling, for example. I’m also checking it using the console, which tells me the same thing: nothing changed.

My eyes, though, tell me something has changed, as I’m seeing “10, omg, moo” instead of “blank, hello world, 2000”. What’s going on?

EDIT: I posted the wrong jsFiddle. This should be the correct one now

Answer by Kolink

There is a difference between the value attribute and the value property. When you type in the input box, you are changing the property, not the attribute. The attribute stays the same as when the document was loaded. Among other things, this means you can reset an input box to its default value with elem.value = elem.getAttribute('value');.

Similarly, if you have a drop-down <select> with one of the options having the selected attribute set, even if you choose a different option that attribute will still be there even though the selected property is now false.

The same applies to checkboxes and the checked attribute. The same also applies for the disabled attribute, and several other things too.

Answer by Starx

It is in-fact changing the DOM, other ways the 10 woulnd’t have showed up in the text area anyway. The problem is in the firebug itself(at list the old one), I am not sure if it is still available in the new ones.

To verify, you can use the web console of firefox or console of chrome.

Read more

how can i make a javascript based form checkbox validate with javascript before sending my form

Question by phj

Hi i have a contact form on my site, In this form i got a javascript checkbox button.

This is the end code of my form: this div tag is my checkbox:

<p><label for="agree">(*) I agree whit the transport terms and conditions:</label><div id="cb"></div></p>
<p>hi
<input name="Submit / Send" type="submit" class="submit" id="Submit / Send" tabindex="370" value="Submit / Send" />
<p id="error_zone" style="visibility:hidden;">Errors: There are some errors in the form. Please correct them.</p>
</p>

This is the javascript text button:

<script type="text/javascript">
    var cbh = document.getElementById('cb');
    var val = '1';
    var cap = '';

    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = val;
    cb.value = cap;
    cbh.appendChild(document.createTextNode(cap));
</script>

also i make use of spry validation for my other form elements.
I would like to validate the checkbox with javascript to create a captcha checkbox!
Is it posible to let pop up a validation masage and and not disturbe the spry validation?!
Its important that if javascript is turned off the form als can’t submit any more.

Hope someone can help me. thanx alot for your time!

i’m trying to encomplish this: http://uxmovement.com/forms/captchas-vs-spambots-why-the-checkbox-captcha-wins/

snippet of spry validation:

<script type="text/javascript">
var errorsOnSubmit = function(form){
 var ret = Spry.Widget.Form.validate(form);
 var errorZone= document.getElementById('error_zone');
 if (!ret){
      errorZone.style.visibility = 'visible';
      errorZone.style.backgroundColor = 'red';
 }else{
      errorZone.style.visibility = 'hidden';
 }
 return ret;
}
</script>
<script type="text/javascript">
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1", {isRequired:false,  invalidValue:"1", validateOn:["blur", "change"]});
var spryselect2 = new Spry.Widget.ValidationSelect("spryselect2", {isRequired:false, invalidValue:"1", validateOn:["blur", "change"]});
var spryselect3 = new Spry.Widget.ValidationSelect("spryselect3", {isRequired:false, invalidValue:"1", validateOn:["blur", "change"]});

Answer by Starx

Give an ID to the checkbox after you created the element

cb.type = 'checkbox';
cb.id = 'mycheckbox';
cbh.appendChild(cb);

Now, you can select the element using document.getElementById('mycheckbox') and the validate it.

Here is a snippet to validate the checkbox

var myform = document.forms("yourformname");
myform.onsubmit = function() {

    //validate the checkbox
    var checkb = document.getElementById('mycheckbox');
    if(checkb.checked != true) { 
       alert('not checked');
    }

    //rest of the validation
};

Update 1:

Haven’t tested but should work

var errorsOnSubmit = function(form){

  //validate the checkbox
  var checkb = document.getElementById('mycheckbox');
  if(checkb.checked != true) { 
     alert('not checked');
  }

 var ret = Spry.Widget.Form.validate(form);
 var errorZone= document.getElementById('error_zone');
 if (!ret){
      errorZone.style.visibility = 'visible';
      errorZone.style.backgroundColor = 'red';
 }else{
      errorZone.style.visibility = 'hidden';
 }
 return ret;
}
Read more

How to add a callback for setAttribute?

Question by Steffi

Is it possible to add a callback on setAttribute on Prototype ?

For this example, I would like to show an alert("done !") when setAttribute() is finished.

img.setAttribute("src", "http://blabla.com/c.jpg");

Answer by alex

You could, but I wouldn’t recommend it.

(function() {

    var elementSetAttribute = Element.prototype.setAttribute;

    Element.prototype.setAttribute = function() {
        whateverFunctionYouWant.call(this);

        return elementSetAttribute.apply(this, arguments);
    }

})();

jsFiddle.

This will call whateverFunctionYouWant() when you do something such as document.links[0].setAttribute('href', '/').

You seem to want this to call a callback when you change the src attribute of img elements and the new resource has loaded…

(function() {

    var HTMLImageElementSetAttribute = HTMLImageElement.prototype.setAttribute;

    HTMLImageElement.prototype.setAttribute = function(attribute, value) {
        var image;

        if (attribute == 'src') {
            image = new Image;
            image.addEventListener('load', loaded, false);
            image.src = value;
        }

        return HTMLImageElementSetAttribute.apply(this, arguments);
    }

})();

jsFiddle.

You could overload setAttribute() here with a third parameter, which would be the callback.

In my opinion and experience, I’d create a different function instead for doing this. Modifying prototypes is one thing, but overloading native DOM methods to do extra things sounds like inviting trouble, especially once a developer unfamiliar with what you’ve done looks at the code.

It goes without saying that if you want the latter example to work < IE9, use the attachEvent() fallback for adding the event listener.

Answer by Starx

May be not the golden solution but

img.setAttribute("src", "http://blabla.com/c.jpg");
img.onload = imageCallback;

function imageCallback() { ... }

If you are interested in jQuery, there is plugin called waitforimages that might help.

Read more

CSS Text on an Image

Question by DJ Howarth

I have the hardest time with CSS because it is so fickle it seems. Need to help with this.

I want my “section.png” image to be the Header Bar, which is clickable, and a table Expands and Collapses as you click the Header Bar.

<table width="100%">
 <tr>
 <td width=80% align=left>
 <font color="white" size="4"><strong>&nbsp;General Airport Information</strong></font>
 </td>
 <td align=right><font color="white" size="2">
    <div id='oc5' style="border-style: none; vertical-align:bottom;">
<img src="http://.../images/expand.png" width="15" height="15" style="border-style: none; vertical-align:top;">&nbsp;Show&nbsp;
</div></font>
</td>
</tr>
</table>
</div>

^^^
Everything in the “Div” above needs to be on top of the section.png image.
^^^

<div id="id5" style="display: none">    

<table width=80% align="center">
<tr align="left">
    <td colspan="2" align="right">
   Hidden text - Until Header Bar is Clicked.
    </td>
</tr>
</table>
</div>

I have looked around for answers, regarding this issue. I know it has to do with CSS and float or position and absolute or relative. IDK, I cant figure it out. Can someone steer me in the right direction.

Answer by Starx

The correct way to do this, would be to set a background instead of adding a image element

<div class="parent" style="background: url('image.jpg'); height: 300px; width: 500px;">
    <div class="text">...</div>
</div>
Read more

Concat SQL Array

Question by oussemos

I want to concat two SQL array in order to have a single JSON result

$sql1=mysql_query("select count(Ip_Routeur) as RouteurDown from Routeurs WHERE Etat_Routeur=0");
$sql2=mysql_query("select count(Ip_Routeur) as RouteurUp from Routeurs WHERE Etat_Routeur=1");
while($row1=mysql_fetch_assoc($sql1))
$output1[]=$row1;
print(json_encode($output1));
while($row2=mysql_fetch_assoc($sql2))
$output2[]=$row2;
print(json_encode($output2));
mysql_close();

Answer by Starx

The codes does not required to combine any array.

You can combine, the two query results with a single query

$sql1=mysql_query("select count(Ip_Routeur) as RouteurDown from Routeurs WHERE Etat_Routeur=0 or Etat_Routeur=1");
$rows = array();
while($row1=mysql_fetch_assoc($sql1)) { 
    $rows[] = $row1;
}
print(json_encode($rows));
mysql_close();
Read more

auto fit image in div / jquery

Question by tintincutes

How can I auto-fit an image if my code is like this:

<script type="text/javascript"> 
jQuery.noConflict();
jQuery(document).ready(function () {
    var count = 0;
    function animate() {
        jQuery(".fadein").eq(count).fadeIn(1000);
        count++;
        if(count <= jQuery(".fadein").length) {
            setTimeout(animate, 1000);
        } else {
            jQuery("a.fadein").fadeOut(1000);
            count = 0;
            animate();
        }      
    }
    animate();
});
</script>

Would this be correct?

<script type="text/javascript"> 
    jQuery.noConflict();
    jQuery(document).ready(function () {
        var count = 0;
        function animate() {
            jQuery(".fadein").eq(count).fadeIn(1000);
            count++;
            if(count <= jQuery(".fadein").length) {
                setTimeout(animate, 1000);
            } else {
                jQuery("a.fadein").fadeOut(1000);
                count = 0;
                animate();
            }      
        }
        animate();
    })
            function fitImagetoContainer() {   $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic   
       }); }

//Call the function at load 
      $(window).load(function() {    fitImagetoContainer(); });


//Also call the function when the window resizes  
      $(window).resize(function() {    fitImagetoContainer(); });;
    </script>

Answer by Starx

Here is my throw at your problem

//Create a function to resize the image with respect to parent
function fitImagetoContainer() {
  $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic
  });
}

//Call the function at load
$(window).load(function() {
   fitImagetoContainer();
});


//Also call the function when the window resizes 
$(window).resize(function() {
   fitImagetoContainer();
});
Read more

echo plus sign php

Question by jose

I’m echoing a php string variable into html

<span class="title_resource">
  <?php echo  $titulo; ?>
</span>

But when the plus sign (+) is present, it turns into a space.

I’ve already tried using urlencode but then I get something like “Constru%25C3%25A7%25C3%”

Should I use something like string replace?

Thanks in advance

Update:

$titulo is setted using $_GET

if (isset($_GET['T']))// title
    $titulo = $_GET['T'];

(…)

More clear, perhaps

I want to send exactly this text “Estudo de ax^2 + bx + c”. The page receives by $_GET. When I print this value I get “Estudo de ax^2 bx c”

Answer by Starx

Its the way values as encoded to be sent over using GET, spaces are converted to + and + are converted to %2B.

If you really want to send the plus symbol over the form, then replace the spaces with plus

$text= str_replace(" ", "+", $text);

Next make sure your form uses correct enctype either application/x-www-form-urlencoded or multipart/form-data

Read more

added a css background, how to entirely remove it

Question by sameold

I’m using the jquery .css property to add a background

myobj.css('background', '#AE0000');

This results in this style html being added to the markup

style="background: none repeat scroll 0% 0% rgb(174, 0, 0);"

Later on, I want to remove this background. I thought that setting css background to white myobj.css('background', '#FFFFFF'); would work, but unfortunately, this creates problems because the div has white background as opposed to nothing.

style="background: none repeat scroll 0% 0% rgb(255, 255, 255);"

Is there a similar way with jquery to entirely remove the background property of the CSS? like style=""

Answer by SiGanteng

Short Answer

myobj.css('backgroundColor', 'transparent');

Long Answer

I’d suggest for better maintainability, use css classes for things like this:

.active { background:#AE00000 }

then in your javascript

myobj.addClass('active');

to toggle off

myobj.removeClass('active');

This has the benefit of you not having to worry about changing the css value (if you use css()) everytime there’s change in your design or if you need to add more markup to that particular element.

For example, in the end you need to use background, font-size and color, in your js:

myobj.css({'background':'#aaa', 'font-size':'15px', 'color':'red'});

Then everytime you need to toggle off:

myobj.css({'background':'none', 'font-size':defaultSize + 'px', 'color':'black'});

Not only it’s error prone, but more difficult to maintain, if you use css:

.active { background:#AE00000; font-size:15px; color:red }

then in your javascript

myobj.addClass('active');

to toggle off

myobj.removeClass('active');

Answer by Starx

I would say, this will be a good way

myobj.css({
  'background': 'none', //remove all the background property
  'backgroundColor': '#FFF' //then only set the background color property
});
Read more
...

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