Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding a close button (Javascript)

Tags:

javascript

Trying to add a 'X' - close button for a google maps marker. The markers will show small on the map but will enlarge when clicked (same marker, just increasing the size). I can add a close button but cannot get it to work (reduce the size back to original). Solutions need to be dynamically added please.

Fiddle: https://jsfiddle.net/gost1zLd/

var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.background = 'black';

var img = document.createElement('img');
img.style.width = '100%';
img.style.height = '100%';
img.src = '';

var exit = document.createElement('div');

function large()
{
    div.classList.add("large");

    if (div.className == "large")
    {
        div.style.width = '300px'; 
        div.style.height = '300px';

        exit.innerText = 'X';
        exit.style.width = '20px';
        exit.style.height = '20px';
        exit.style.fontSize = 'xx-large';
        exit.style.fontWeight = 'bold';
        exit.style.color = 'white';
        exit.style.position = 'absolute';
        exit.style.top = '5px';
        exit.style.left = '265px';
    }
}

function close()
{
    div.classList.remove("large");
}

document.body.appendChild(div);
div.appendChild(img);
div.appendChild(exit);

div.addEventListener('click', large, false);
exit.addEventListener('click', close, false);
}       
like image 772
user4612360 Avatar asked Jun 15 '26 23:06

user4612360


1 Answers

The problem is that removing the class large is not enough to reset the <div> to its original state since class large in itself is meaningless because it has no CSS definition. My advice is to move the styling to CSS instead of JavaScript. See fiddle: https://jsfiddle.net/gost1zLd/1/.

like image 133
Griffith Avatar answered Jun 17 '26 11:06

Griffith