jQuery/Javascript: populate div with data written by a script than store the div's value into a cookie

386 views Asked by At

I have the following scenario:

User hovers over a menu item and on hover a Javascript script is called from an external site. This script writes content to a specific div.

What I then need to do is grab this divs html and store it in a cookie. The cookie expires after 3 minutes.

The second time the user hovers within the 3 minutes (cookie has not expired yet), instead of calling the Javascript from the external site, I need to simply load the HTML that was previously written to the div by the Javascript from the external site. This is to limit the amount of calls to the external site, since it charges for each call to their server.

Because the writing of the content from the Javascript of the external site and assigning the written html values to the cookie are happening at the same time client side, I'm always getting no value when trying to store the html into a cookie.

Somehow I need to wait until the page has loaded fully, so that the external script has populated the specified div with HTML content, and THEN add that divs html content to the cookie.

This is where I"m stuck. And perhaps there is an easier, smarter approach to this? I"m open to suggestions and ideas!

Here is the code I have with comments:

$(document).ready(function() {

    // create script element
    var my_script = document.createElement( 'script' );
        my_script.type = 'text/javascript';
        my_script.src = "http://www.external-site.com/this_script_writes_content_to_div.js";

    // User hovers on a menu item, limit the call by using jQuery .one
    $( "#my_menu_item" ).one( "mouseenter", function() {

        // If cookie exists, don't write Javascript (my_script) but use stored value in cookie
        if (document.cookie.indexOf("my_cookie") != -1) {

            // This is where I'm having trouble, since the cookie's value is empty, see below
            $("#div_with_content_from_js").html( getCookie("my_cookie") );

            // Test results
            console.log('Cookie exists');
            console.log(getCookie("my_cookie"));
        }

        // If cookie does not exist, write the script to a div
        // the script will then populate another div with content, the div name is 'div_with_content_from_js'
        // then create cookie and store the other divs content into the cookie
        else {
            document.getElementById( "div_for_external_script" ).appendChild( my_script );
            create_my_cookie();

            // test results
            console.log( 'Cookie does not exist' );
        }
    });

});


// Creates a cookie that expires after 180 seconds (3 minutes)
function create_my_cookie() {
    var date = new Date();
    date.setTime( date.getTime() + ( 180*1000 ) );
    var expires = "; expires="+date.toGMTString();

    // this value returns empty because the html value of div_with_content_from_js was just written (see else part above)
    // this is where I'm stuck, how do I get the value of div_with_content_from_js and store it in the cookie
    var coffee_cookie_value = $("#div_with_content_from_js").html();

    document.cookie = 'my_cookie' + "=" + coffee_cookie_value + expires + "; path=/";

    // test results
    console.log( coffee_cookie_value );
    console.log( getCookie( "my_cookie" ) );
}


// This function returns a specific cookie, used for testing
function getCookie( name ) {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec( document.cookie );

    return ( value != null) ? unescape(value[1] ) : null;
}
3

There are 3 answers

1
dm4web On
  1. The cookie is used only for the countdown 3 minutes
  2. Add a hidden div on the page
  3. In a hidden div store content from an external website
  4. On hover: if not expired 3 minutes just copy the content of the hidden div
0
whodell On

Would the jQuery .always() function be of any use here? In jQuery, your "always" function will execute AFTER the preceding code has resolved.

$( "div_for_external_script" ).appendChild( my_script ).always(function() { create_my_cookie(); };
0
Bogdan Kuštan On

Why not to use MutationObserver? Then You could set cookie when needed mutation occurs. Sample fiddle setTimeout is only for demonstration purposes. so your code should be something like:

// If cookie does not exist, write the script to a div
// the script will then populate another div with content, the div name is 'div_with_content_from_js'
// then create cookie and store the other divs content into the cookie
else {
    var target = document.querySelector('#div_that_will_be_populated');
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if(mutation.type == 'childList') {
                create_my_cookie();
            }
        });    
 });
 var config = { attributes: true, childList: true, characterData: true };
 observer.observe(target, config);
 document.getElementById( "div_for_external_script" ).appendChild( my_script );

 // test results
 console.log( 'Cookie does not exist' );
}