I'm having trouble with data attributes in some basic html and javascript. I have several links throughout a page that dynamically insert a map and a 'close' link to get rid of the map.
The links are all similar to:
<a class="maplocation" href="#" data-coords="4645/234234" data-zoom="9">Link text<span class="mapslideicon"></span></a>
And the javascript on clicking these links is:
$("a.maplocation").click(function() {
if ($(this).data("mapopen") == true) {
// Map already clicked and open, do nothing
} else {
var timeStamp = $.now();
var mapID = "m_"+timeStamp;
var mapCloseID = "c_"+timeStamp;
var anchorID = "a_"+timeStamp;
var mapClass = 'widemap';
var mapDiv = $("<div class='"+mapClass+"' id='"+mapID+"'> </div><a href='#' id='"+mapCloseID+"' class='maplocationclose'>close</a>");
mapDiv.insertAfter($(this).parent());
// Set a data attribute on the link to let it know a map is open
$(this).data( "mapopen", true );
// Set a data attribute on the link so that we can reference it from the close button
$(this).data( "anchorid", anchorID );
}
return false;
});
This creates a div for a map, places a data attribute on the original anchor to say that the map is open and also creates an anchor for closing the map.
When the close map anchor is clicked it executes the following:
$('body').on('click', 'a.maplocationclose', function(){ // delegated.
var id = $(this).attr('id');
idNo = id.split("_");
var assocMapID = "m_"+idNo[1];
var assocAnchorID = "a_"+idNo[1];
$("#"+id).remove();
$("#"+assocMapID).slideUp( 300, function() {
$("#"+assocMapID).remove();
});
// Set a data elemt on the original map link that let's us know the map is closed again
$('.maplocation[anchorid="'+assocAnchorID+'"]').data( "mapopen", false );
return false;
});
This all works but I'm having difficulty in accessing the data-attribute from the close anchor. It references fine from the original link, as I intended, and sets the mapped attribute as true and reads it as true. However, when I set it to false in the close anchor it cannot find it and it's never set.
I've run a test (from inside the maplocationclose function) to see if I can find any data attributes from the anchor, such as:
console.log("Zoom Attr is: " + $('a.maplocation[anchorid="'+assocAnchorID+'"]').data('zoom'));
And they're returning 'undefined'.