I am using the bootstrap popover and i wanted to add certain elements to the DOM. I am adding an additional element to the title using:
$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">×</span>');
However if i dont refresh the page, the ('div.popover')
keeps prepending the <h3>
element and i have duplicate titles seen in the popover. something like screenshot below:
Can anyone help me in setting the element to null, so that when i search again ( w/o refresh), it wont show me duplicate title names.
Thanks!
You can only append when its not already present in the DOM using
if ($('h3.main-header-title').length==0) {
$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">×</span>');
}
You can achieve this using javascript only by
var element = document.getElementsByClassName("main-header-title");
if (element.length ==0)
{
$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">×</span>');
}
Or you can remove them after some time (say 1sec) when they are added to DOM
setTimeout(function(){
$("h3.main-header-title").remove();
// or $("h3.main-header-title").fadeOut(100); for animated removal
},1000);
And for better UX if you want to re-display the popover, do it this way.
if ($('h3.main-header-title').length==0) {
$('div.popover').prepend($('<h3>').html('Accounts Already exists').addClass('main-header-title'));
$('.main-header-title').append('<span class="close" id="cross-button">×</span>');
}
else {
$(h3.main-header-title).fadeOut(200);
setTimeout(function(){$(h3.main-header-title).fadeIn(200);},500)
}
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.