Publifiedlabs Publifiedlabs - 2 months ago 41
jQuery Question

How to prepend only once in jQuery in a Wordpress environment

I am working in a Wordpress Environment. I inserted a custom section by using jquery to show a "Treasure Trove" icon so people can click on it. This icon is prepended to the default "Red Chat Icon" that is created through a chat plugin.

This makes the DIV i created directly related to the "Red Chat Icon". However whenever I open and close the default chat icon the treasure trove icon duplicates every time. How would I go about making the "Treasure Trove" icon to not duplicate every time it is opened and closed?

example

jQuery

jQuery(document).on("wplc_animation_done", function(e) {

jQuery( "#wp-live-chat-header" ).append( "<div class='wp-live-chat-extend'><h2>Chat with Us!</h2></div>" );

jQuery( "#wp-live-chat" ).prepend( "<a href='/exatactical/treasure-trove/'><div id='pbf-treasure-trove' class='pbf-treasure-trove-bg'></div></a>" ); // This is what inserts the icon
jQuery( "#pbf-treasure-trove" ).append( "<div class='wp-live-chat-extend'><h2>Treasure Trove</h2></div>" );
});


CSS

.wp-live-chat-extend {
opacity: 0;
width: 72px;
height: 72px;
}

.wp-live-chat-extend:hover{
padding-left: 90px;
opacity: 1;
}

.wp-live-chat-extend h2 {
color: #fff!important;
font-size: 20px;
width: 200px;
margin-top: 20px;
}

#pbf-treasure-trove {
margin-bottom: 15px;
background-image: url(/exatactical/wp-content/uploads/2017/08/iconRetina.png);
background-size: cover;
}

#pbf-treasure-trove:hover {
background-image: url(/exatactical/wp-content/uploads/2017/08/iconRetina2.png);
background-size: cover;
}

.pbf-treasure-trove-bg {
border-radius: 62px 62px;
background: #00ADEF;
width: 62px;
height: 62px;
}

Answer Source

You should be able to exploit jQuery's .one() method.

jQuery(document).on("wplc_animation_done", function(e) {
    jQuery( "#wp-live-chat-header" ).append( "<div class='wp-live-chat-extend'><h2>Chat with Us!</h2></div>" ); 
    jQuery( "#pbf-treasure-trove" ).append( "<div class='wp-live-chat-extend'><h2>Treasure Trove</h2></div>" );
}).one("wplc_animation_done", function(e) {
    jQuery( "#wp-live-chat" ).prepend( "<a href='/exatactical/treasure-trove/'><div id='pbf-treasure-trove' class='pbf-treasure-trove-bg'></div></a>" ); // This is what inserts the icon
});

If necessary, the other two lines can also be shuffled into the .one() handler.