March 4, 2016

JS/HTML – onresize doesn't fire

LastSecondsToLive’s Question:

I wanted to add the resize event to an element (I know you can’t add resize to a specific element, but it would be fine if the JS-function would be triggered on a resize of any kind – not the specific element).

I was thinking about this:

<div onresize="wrapperResize();"></div>

This somehow doesn’t work (Safari user here). This however works:

<div onclick="wrapperResize();"></div>

Currently wrapperResize() only holds a simple console.log(). What could I do about this?

PS: This works great (traditional checked), what do I even do different?

EXTRA: The div has a fixed height and 33% of the body element wide. Even though the event should fire, when the window is resized I thought this may be the cause.

I think you should set onresize handler on window and do it in javascript, not inline html.. Like so

window.onresize = yourFunction

You cannot attach a onresize event on a <div> container. It is only available for window for most of the browsers.

July 26, 2013

on blur of input field validate field and cancel blur event if not valid

Xavier DSouza’s Question:

I am validating a field on blur event. And if the field is invalid I want the focus to remain in same field and not go to next field. When I do $(this).focus() within my blur function it only works in Chrome and not in Firefox. I tried the settimeout function but the problem is that the focus goes to next field(#myInput2) and then comes back to field(#myInput1). I dont want that as the next field also raises error cause it will be blurred again and it is empty. Is there a way to solve this in Firefox??
My code :

$('#myInput1').blur(function () {
    if (!validField1($(this).val())) {
        alert("Invalid");
        $(this).focus(); // Does not work in FF 
    }
});


$('#myInput2').blur(function () {
    if (!validField2($(this).val())) {
        alert("Invalid");
        $(this).focus();
    }
});

I asked this question once, these are generally browser features which is not lock down a user to one input box. User should have choice of going away if they wanted, whether or not it is valid.

So, Focus the same element after the blur event is disallowed.

March 7, 2013

Reload parent dialog content when child dialog is closed

Question by user1277546

I have a large jQuery dialog window that opens up many more dialog windows inside when buttons are clicked in the parent dialog window for updating the database.

I want to update the parent window when the child dialogs are closed.

I can see how to do this with event close and load(url) but how do I make the association between child and parent without specifying each and every ID.

Answer by Starx

Without some markup structures, I cannot understand how your child dialogs resides inside parent.

jQuery has a function called .closest() that travel up the DOM tree to find the nearest matching selector, so you can use this by giving a class to the parent dialog. And select them, when you want to use it like.

$(this).closest(".parent").html("Updated Content");
// ^ Represent your child dialog as you want
February 27, 2013

jQuery On() is not working for $(document)

Question by Jason Biondo

I am currently in the process of integrating the dropkick.js plugin into my app, but I have run into a few snags. When I change backbone views the events do not work properly and the .live() event associated in dropkick.js just flat out doesn’t work at all. Nothing fires. I decided to upgrade this to using the .on() function and got it sort of working (even though it still deletes my url for some reason).

This doesn’t work at all:

$(document).on("click", ".dk_toggle", function() {

This only works somewhat:

$(".content").on("click", ".dk_toggle", function() {

Do you know why document doesn’t work at all?

My backbone $el is $(".content").

Answer by Starx

Instead of document, use body. It basically gives the same behavior.

$('body').on("click", ".dk_toggle", function() {
//....
});
November 8, 2012

Using onChange on Select Option

Question by deetu

I have a select option box that is dynamically populated, so if i change the select some other boxes are filled, and i can delete them too.
Which also deletes the option from the select box, this works fine, but when i delete the options and i have just one left in the box, there seem to be no way to fire the option.

$("#email_name").on("change", function(){
    var componentkeys = myDailyemail.getKeys($("#Component").val());
    $.each(componentkeys, function(kIndex, kItem) {
        $("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
    });
});

Answer by iMoses

You can automatically trigger a change event after you populated the select element, making it as if the user already selected the first option.

$("#email_name").on("change", function(){
    var componentkeys = myDailyemail.getKeys($("#Component").val());
    $.each(componentkeys, function(kIndex, kItem) {
        $("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
    });
    $("#key").trigger("change"); // trigger key
}).trigger("change"); // trigger email_name

I wasn’t sure what you wanted to trigger so I entered both possibilities.

Answer by Starx

You can use .trigger() to fire events manually.

Insert following, where needed.

$("#email_name").trigger('change');
April 23, 2012

Call function when adding a div to my site

Question by ifsession

I have a script which adds a div to my site when I upload a photo. Now I wan’t to call a function when this div gets added. I’ve tried this, but it doesn’t work.

var divImg = document.createElement("div");
divImg.id = "divimg";
newImg.setAttribute('onload','urediBtnx(this)');
divImg.innerHTML = '<a href=""><img src="/imago/images/btnx.gif" class="btnx"></a>';

It should call this function:

function urediBtnx(dv){
    alert("blabla");
}

The thing is, if I do it this way, then the function gets called, but I need to get the div, not the img.

divImg.innerHTML = '<a href=""><img onload="urediBtnx(this)" src="/imago/images/btnx.gif" class="btnx"></a>';

Answer by Christophe

You can attach onload event handlers to element like body, img, script or iframe, but not to a div.

In your scenario, the div is the grand-parent of your image. You can keep the onload on the image, then use this.parentNode.parentNode to reach the div.

Answer by Starx

Div does not have an onload event. They are only availabe for <body>, <frame>, <frameset>, <iframe>, <img>, <link> or <script>.

Subsequently calling the function after its added to the DOM is a way.

parent.appendChild(divImg);
urediBtnx();

The possibility of a callback can be gained if you are jQuery library

$("#parent").append($(divImg), function() {
    urediBtnx();
});
April 18, 2012

'div_element' is null or not an object in IE7

Question by nic

here i have get one error in java script ‘div_element’ is null or not an object.
i have given my code below

function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}

when i debugging my script so it’s working fine in other browser including IE 8. but it’s not working in IE 7.i don’t understand what exact issue occur in this script.

Thanks in Advance.

Answer by Starx

First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.

Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.

Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.

function showLoading(id) {

    div_element = $("#" + id);
    console.log(div_element); //check the console to see if it return any element or not
    div_element.html(loading_anim);

}
April 16, 2012

Adding two click events to the same button only works once

Question by bob_cobb

Basically I’m trying to make a button be able to handle editing of an element. I want it so that when I click on the Edit button, it changes the text to Save Changes and adds a class which will then bind the button to another click event so that when they click Save Changes, it’ll alert Saved and change the text back to Edit. It does this perfectly once. If you continue to try to do it, it simply won’t add the class or change the text anymore.

Here is a demo on jsfiddle

The code:

$(function() {
$button = $('button[name="edit"]');
$button.on('click', $button, function() {
    var $that = $(this);
    $that.text('Save Changes');
    $that.addClass('js-editing');
    if ($that.hasClass('js-editing')) {
        $that.off('click').on('click', $that, function() {
            alert('Saved!');
            $that.text('Edit');
            $that.removeClass('js-editing');
        });
    }
});

});​

Answer by qw3n

Try this http://jsfiddle.net/bpD8B/4/

$(function() {
    $button = $('button[name="edit"]');
    $button.on('click', $button, function() {
        var $that = $(this);
        if($that.text()=='Edit'){
          $that.text('Save Changes');
          $that.addClass('js-editing');
        }
        else{
                alert('Saved!');
                $that.text('Edit');
                $that.removeClass('js-editing');
        }
    });
});

Answer by Starx

This is just a logic problem. And with $that.off('click').on('click', $that, function() { you are delegating to itself, which is not how you should do it.

Here is a solution using your code:

$(function() {

    $button = $('button[name="edit"]');
    $button.on('click', $button, function() {
        var $that = $(this);
        if ($that.hasClass('js-editing')) {
            alert('Saved!');
            $that.text('Edit');
            $that.removeClass('js-editing');        
        } else {      
            $that.text('Save Changes'); 
            $that.addClass('js-editing');
        }
    });

});​

Demo

April 15, 2012

is it possible to capture scrollstart on an element other than $(document) in Jquery/Javascript?

Question by frequent

I’m trying to use the Overthrow Plugin, which is a polyfill for overflow:auto on mobile devices. Sample here.

My question:
How can I detect scrollstart/scrollstop on a div.element that is scrollable? Is this possible at all, or do the scroll/scrollstart/scrollstop events only work on $(document)?

Specifically, if I have two panels on my page, which both are scrollable, is there any way to make this work:

 $(document).on('scrollstart','div:jqmData(panel="main"), div:jqmData(panel="menu")'), function() {
    console.log("scroll detected");
    });

Thanks for some inputs!

EDIT:
My HTML looks like this:

<html class="ui-popover-mode">
// OR depending on screen size
<html class="ui-splitview-mode">
   // panel 1
   <div data-panel="main" class="ui-panel">
       <div data-role="page" class="ui-page" id="mainOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="mainTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
   // panel 2
   <div data-panel="menu" class="ui-panel">
       <div data-role="page" class="ui-page" id="menuOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="menuTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
   // panel 3
   <div data-panel="pop" class="ui-panel">
       <div data-role="page" class="ui-page" id="popOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="popTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
</html>

Screen Mode is set depending on screen size. In every panel there can be multiple pages, which each have a content section, which is scrollable using overthrow.

I want to bind to scrollstart in main and menu content section in splitview-mode AND main content sections in popover-mode.

Originally my selector tried to capture this and only attach to the relevant content elements:

$(document).on('scrollstart','.ui-splitview-mode div:jqmData(panel="main") .ui-content,  .ui-splitview-mode div:jqmData(panel="menu") .ui-content, .ui-popover-mode div:jqmData(panel="main") .ui-content, ', function() {
        // do sth
    });

Agreed this is complex and did not work. But it attached events only to the necessary elements. Now I’m doing like this:

$('.ui-content').on('scrollstart', function() {
        // check here if .ui-content is on the correct panel
    });

So I now have a lot of unnecessary bindings and only check if the binding is correct after the event is detected vs. the other way I would only attach the event to the required elements.

That’s what I was wondering.

Answer by Starx

You can directly select the element and attach the scroll event. Simple example

$("#selector").on('scrollstart', function() {
    //...do stuff
});
March 30, 2012

how to button enable when all textbox has value in jquery?

Question by nic

i am new in programming.here i have given description of my problem
i have one pair of two text box. one text box is for url and other is for instruction but all text-boxes created dynamically depending on what value comes from database.

for example $testing_type_id=2 so i get total two pair of text boxes ,let it called bundle.$i is used for indentify textbox uniquely.

  <input type = "text"  size="33"   class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
             <input type = "text"  class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value=""  /> <br/>
             <input type="submit" name="checkout" id="checkout"   class="graybtn1 ptr  button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />

here what i wanted to do that if all bundle has value, either in one textbox or both textbox so and so enable submit button.if i removed value so disable submit button using jquery.

need a help urgent.Thanks in Advance.

Answer by Sheikh Heera

I think this will work

$(document).ready(function(){
    $("input[class^='uploadtxt']").keyup(function(e){
        var alltxt=$("input[class^='uploadtxt']").length;
        var empty=true;
        $("input[class^='uploadtxt']").each(function(i){
            if($(this).val()=='')
            {
                empty=true;
                $('#checkout').prop('disabled', true);
                return false;
            }
            else
            {
                empty=false;
            }
        });
        if(!empty)  $('#checkout').prop('disabled', false);                    
    });
});​

An example is here.

Answer by Starx

I am going to suggest a minor markup changes so that will be easy to handle the traversing.

Wrap the elements in a <div>

<div class="item">
    <input type = "text"  size="33"   class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
    <input type = "text"  class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value=""  /> <br/>
    <input type="submit" name="checkout" id="checkout"   class="graybtn1 ptr  button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
</div>

Then, Attach a snippet on the change event

$("input[type=text]", $(".item")).change(function() {
    var allField = true;
    $(this).closest(".item").find("input[type=text]").each(function() {
         allField = allField && ($(this).val().length > 0)
    });
    if(allField) {
        $(this).closest(".item").find("input[type=submit]").prop('disabled', false);
    }
});

Demo of Working Solution

...

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