Reputation: 7
Problem is that jQuery doesn't add CSS to appended input. I have also created demonstration http://jsfiddle.net/heY2u/
HTML:
<div id='container'></div>
<input type="text" value="Test1">
JS:
$('input, textarea, select').on('focusin', function () {
$(this).data('holder', $(this).attr('placeholder'));
$(this).attr('placeholder', '');
$(this).css('outline', '#F78181 solid 1px');
});
$('input, textarea, select').on('focusout', function () {
$(this).attr('placeholder', $(this).data('holder'));
$(this).css('outline', '');
});
$('<input type = "text" value = "Test2">').appendTo('#container');
alert(123);
Upvotes: 0
Views: 77
Reputation: 207923
You need to put the line:
$('<input type = "text" value = "Test2">').appendTo('#container');
before your other jQuery. It's failing because the syntax you're using will only apply the code to elements already in the DOM. So you would need to add your element to the DOM first, and then apply the other code.
Or, use .on()'s delegation syntax like:
$(document).on('focusin', 'input, textarea, select', function () {
This will allow you to bind the events to any elements in the DOM already, and any elements you dynamically add later on.
From the docs:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
Upvotes: 1