I'm having an issue with my code generation from an XHR request. The old javascript doesn't work on newly generated elements, therefore I must repeat code. I tried to handle this using the $(this) element, but old elements seem to be having multiple code events based on how many generations have occurred (code is being repeated).
I have gotten it to work using a dynamically changing class (.load_1, .load_2, .load3, etc...) that I assign to all new elements then pass as the $this, however this requires a lot of needless code.
Is there a simpler way of repeating js code to allow newly generated elements to function and maintaining the code from old elements that already exists (without code being repeated, i.e. first elm: two button presses after first generation, three button presses after second generation).
Calling threebar function after XHR request:
- $_rtn is from the server, giving the dom the num of items returned and the HTML generated by the database.
- $_rtn = [$num.'HTML']
if ($status == 200) {
$_rtn = $_rtn.split('|,')
if (parseInt($_rtn[0]) > 0) {
posts.append($_rtn[1]).ready(function() {
load_threebar($(this))
post_media_click($(this))
})
}
}
Threebar Function:
- This allows a button to be clicked and for built-in HTML to be generated that asks the user for an input.
- Every time a .threebar is clicked; I want all other .threebars that are open, to be closed.
- Currently, if a generated elem has an even number of click events, it closes immediately after opening. If it has an odd, it functions as it should.
function load_threebar($loadElem) {
$loadElem.find(' .btn-threebar .threebar').click(function() {
console.log('test')
$this = $(this).parent()
$('.threebar-list').fadeOut(150, function() {$(this).parent().removeClass('threebar-open'); $(this).remove();})
if ($this.hasClass('threebar-open')) {
$this.removeClass('threebar-open').find('.threebar-list').fadeOut(150, function(){$(this).remove()})
} else {
$this.addClass('threebar-open')
gen_threebar($this)
}
})
}
Thank you for any help you can give!