Y.Hewa Y.Hewa - 1 month ago 6
CSS Question

jquery toggle img click and store or remove img id from local storage when clicked

My HTML code looks like this (shown below).

<div class='row hide' data-step='{$row['qid']}' data-title='{$row['question']}'>";

while($row1=mysql_fetch_array($result1,MYSQL_ASSOC)){
echo "<div class='col-lg-3 col-md-4 col-s-6 thumb' >
<a class='thumbnail btt' href='#' id='{$row1['imageid']}'>
<img class='' src='{$row1['thumbpath']}' alt=''>
<div class='overlay'> </div>
</a>
</div>";
}
echo "</div>";


The images will show one by one by going through the loop and I have added overlay so when it is clicked it will be the highlighter. I have made it possible for a user to select more than one image. so you could have more than one image highlighted.

When the image is clicked i store its id in a local storage. Right now my jquery is :

function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}

$(function () {
$('.btt').click(function () {
var id = $(this).attr('id');
storeId(id);

$('#currentLCV').text(localStorage.getItem('reportArray'));
});
});

$('.btt').click(function(){
$(this).toggleClass('overlay overlay2');
});


I can display the local storage values in the HTML again through a div with class #currentLCV so this working now a problem.

However, I want kind of a toggle option where if the user clicks the image it will save the id in the local storage and if the user clicks the same image again the id will be removed from the local storage.

Can someone help, please?

Answer

You can use something like this:

function storeId(id) {
    var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
    if (ids.indexOf(id) === -1) {
        ids.push(id);
        localStorage.setItem('reportArray', JSON.stringify(ids));
    }
}

function unStoreId(id) {
    var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
    var indx = ids.indexOf(id);
    if (indx !== -1) {
        ids.splice(indx,1);
        localStorage.setItem('reportArray', JSON.stringify(ids));
    }
}

$('.btt').click(function () {
    var id = $(this).attr('id');
    $(this).toggleClass('overlay overlay2 stored');
    if($(this).hasClass("stored")) {
        unStoreId(id);
    } else {
        storeId(id);
    }

    $('#currentLCV').text(localStorage.getItem('reportArray'));
});

Note: joined the .btt events together and removed the function wrapper.

Comments