element.html() return empty on DOM ready - javascript

I am working on a countdown timer, using http://keith-wood.name/countdown.html.
My code looks like this,
$('.clock').countdown({until:new Date(2012, 11, 31), format: 'odHMS', onTick:watchCountdown, tickInterval:5, layout:
'<div id="timer">' +
'<div id="timer_labels">'+
'<div id="timer_months_label" class="timer_labels">Months</div>'+
'<div id="timer_weeks_label" class="timer_labels">Days</div>'+
'<div id="timer_days_label" class="timer_labels">Hours</div>'+
'<div id="timer_minutes_label" class="timer_labels">Minutes</div>'+
'</div>'+
'<div id="timer_months" class="timer_numbers"><span class="divide"></span><span>{onn}</span></div>'+
'<div id="timer_days" class="timer_numbers"><span class="divide"></span><span>{dnn}</span></div>'+
'<div id="timer_hours" class="timer_numbers"><span class="divide"></span><span>{hnn}</span></div>'+
'<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span>{mnn}</span></div>'+
'</div>'
});
As you onTick I call a function that looks like this,
function watchCountdown(periods) {
var $div = $("#monitor");
var html = $div.html();
var checking = setInterval(function() {
var newhtml = $div.html();
if (html !== newhtml) {
myCallback($div);
}
},100);
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
}
In the function above there is a check for html != newhtml however html is returning as an empty variable evening though there is HTML in the #monitor element. How can I make it realise there is content to check against?

You don't understand what is DOM ready, it fires only once, when the DOM is fully loaded and rendered from the server.
If you change the DOM with javascript, it has no effect on the DOM ready event.
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
The code above will not cause delay or trigger again the DOM ready event.

Related

jQuery append function is just appending the html but not the classes related to it

I am using php laravel and so it uses blade template to render the views. Following is the javascript code to append html script :-
$(function () {
var count = 0;
$("#min_bonus_value").click(function () {
count++;
var min_bonus_html =
'<div class="min_bonus_row">' +
'<hr>' +
'<div class="row">' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<label for="bonus_day[' + count + ']">#lang('admin.message759')<span class="text-danger">*</span></label>' +
'<select class="select2 form-control" id="bonus_day[' + count + ']" name="bonus_day[' + count + '][]" data-placeholder="#lang('admin.message759')" multiple>' +
'<option value="1">Monday</option>' +
'<option value="2">Tuesday</option>' +
'<option value="3">Wednesday</option>' +
'<option value="4">Thursday</option>' +
'<option value="5">Friday</option>' +
'<option value="6">Saturday</option>' +
'<option value="7">Sunday</option>' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
Following is the piece of blade template code where the above html needs to be appended, I want to append 'select2' class which is styled to select multiple days, but in vain :-
<div id="minimum_bonus">
</div>
I may be off here but when you say "not the classes", do you actually mean the Javascript/jQuery funcionality?
If so, I'll try to explain what is happening: when you initialize a jQuery plugin, like select2, it acts upon what exists in the DOM at the moment you initialize it. So if you later create new items, these won't have the select2 functionality, unless you initialize it again for said new items.
I suggest you create a function to initialize select2 and call it whenever you add new elements to your DOM. You'd need to somehow single out the elements that have already been initialized. You can do so with a class, in this example, the class is 'select2-enabled'. Like this:
function initSelect2() {
$(".select2").each(function(){
if (!$(this).hasClass('select2-enabled')) {
$(this).addClass('select2-enabled');
$(this).select2({
// all your select2 options
});
}
});
}
And then, after you append your new html, you can call your function to initialize select2 on the new elements:
$(parentElement).append(newHTML);
initSelect2();

jquery call function from dynamic div

I am using jquery. I have a div that is populated by jquery. Inside div, there is a list of items under row tag. And, Inside, the dynamic div section, I also have a anchor tag. On clicking on that anchor tag, I want to call the ajax function. Is it even possible?
var content='';
$.each(products, function(key, value) {
content += '<div class="row">' +
'<img src="' + value.image + '" class="img img-responsive" style="height: 65px;"/>' +
'<h3>' + value.name + '</h3>' +
'<p>' + value.category + '</p>' +
'</div>' +
'Delete' +
'<hr>';
});
modal.find('.modal_product_list').html(content);
When the anchor tag is clicked, I want to call ajax function. Here is my ajax sample:
$('.delete_product_from_space').on('click', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});
The on click event is never fired. Is it possible to call like this? Or I am approaching in a wrong way?
You may try to add the event on modal, as the dynamically generated elements would not be available at the time of code execution. Try the below code,
$('.modal_product_list').on('click', '.delete_product_from_space', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});

Jquery attribute not being added to div element

I have a div as follows
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
I am trying to add an attribute to #t1 in the following function.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
But the attribute is not being added. I am not getting a text in the tooltip. what's the issue here?
Note that noOfDatasets is 0.
To answer your question, the issue in your code is the order is is executed.
When the function appendCreateprojectDisabled(noOfDatasets) is executed, it looks for the element $("#t1"), which does not exists yet since the following string has not been added to the HTML document yet:
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
As you may notice, the above code has the element id="t1", which doesn't exists at the time the function appendCreateprojectDisabled(noOfDatasets) is called.
You created the div here dynamicly in javascript, so you just have a string here.
There is two way for you.
First you should write in on the page.
var htmlString = '<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>';
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
$("#aDivInYourPage").html(htmlString);//after register your div you can find your 't1' div. if not it will be undefuned for you.
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
The other way is you can put a spetial character to your div like {TitleAttribute} and replace this with your attribute like title='No datasets available'
you can achieve this by parsed the string to HTML element.
Try this code.
$(document).ready(function () {
function appendCreateprojectDisabled(noOfDatasets, divElement) {
var classAppend = '';
if (noOfDatasets == 0) {
divElement.find("#t1").attr('title', 'No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
var divElement = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'</div>' +
'</div>'
divElement = $(divElement);
var paraElement = '<p><span>Create Project</span></p>'
divElement.find("#t1").append($(paraElement));
$(document.body).append(divElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
Do something like this:
var classAppend = "";
var classAppend = appendCreateprojectDisabled(noOfDatasets);
After making sure classAppend have some value; you can append your html wherever you want.
var html = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'<p><span>Create Project</span></p>' +
'</div>' +
'</div>';
Use this piece of html wherever you want now. The below function is called first.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}

How to write into div using javascript

I want to make a for example content variable in javascript which will have a html tags inside with certain values.
How can I put that in the div when button is pressed.
For example :
This is a content which I want to use:
var contentString = '<div id="info">'+
'<h2><b> Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style=width:220px;display:inline-block;>'+
'<p> Name: '+ this.name + '</p>' +
'<p> Last name: '+ this.last+ '</p>' +
'<p>
'</div>'+
'</div>'+
'</div>'+
'</form>';
And I want to put it into : <div id=something"></div>
In javascript I can have something like:
$("#button").on('click', function() {
// What to put in here?
});
How can I put that in the div when button is pressed.
Like this:
$("#button").on('click', function() {
$('#something').html(contentString);
});
More info about html();
http://api.jquery.com/html/
It goes like this:
$("#button").on('click', function() {
$("#something").html(contentString);
});
If I'm not misunderstanding, then this will work:
$("#button").on('click', function() {
$('#something').html(contentString);
});
This does, of course, assume that you have an element with an id of button (though I assume you do, otherwise you wouldn't have put that jQuery).
JS Fiddle demo.
References:
html().
You should fix up your markup. You have unbalanced elements, and you can't have new lines in the string without escaping it. Try this instead:
var contentString = '<div id="info">'+
'<h2><b style="text-indent: 40px">Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style="width:220px;display:inline-block;">'+
'<p style="text-indent: 1em">Name: '+ this.name + '</p>' +
'<p style="text-indent: 1em">Last name: '+ this.last+ '</p>' +
'</div>';
Note that I skipped the and replaced them with style attributes. You really should put these styles in a stylesheet, though.
$("#button").on('click', function() {
$('#something').html(contentString);
});
Keep in mind that the variables in contentString will not be evaluated when the click event on the button fires, meaning that this.name and this.last will not change. Do you need to update these values on click as well?

Adding html elements from variable using jquery?

I am trying to add elements to specific div, but not using clone(), because i need fresh copy of original elements on every add, mainly because elements are draggable and their values are being change by user? So i have my html in variable, i need to take this elements and add them on click to another elem. ?
$(document).ready(function (e) {
var $gElem = $(
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
);
$('.mainSearch').html($gElem); // initial load of element
$("#combobox100").combobox();
$("#combobox200").combobox();
var counter = 1;
$('.add').live('click', function () {
if ($('.distributionWrapper').length === 6) return;
//var el = $('.distributionWrapper:first').clone().attr('id', 'element_' + ++counter).appendTo('.mainSearch');
$('.mainSearch').add($gElem).attr('id', 'element_' + ++counter);
// here on click add gElem to .mainSearch and set atribute to .distributionWrapper
});
$('.clear').live('click', function () {
if ($('.distributionWrapper').length === 1) return;
$(this).parents('.distributionWrapper').remove();
});
});
Any ideas?
try this
$('.mainSearch').append($gElem);
$('.mainSearch').children('.distributionWrapper:last').attr('id', 'element_' + ++counter);
Store the html as a string in a javascript variable and create a jQuery element every time you need one from that string.
var elemHtml =
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
$(function(){
//your initial element
var $elem1 = $(elemHtml);
}
function someHandler(){
//you can create fresh new elements anywhere without cloning
var $elem2 = $(elemHtml);
}
The duplicate IDs need to be removed. But that's outside the scope of your question.

Categories