Home > Back-end >  automatically remove a div with javascript
automatically remove a div with javascript

Time:10-02

I have a “noticeboard” that displays upcoming events that are occurring in the community.

Each Event is constructed as follows:

<div class=”image” id=”30-9-21” data-name=”Thursday”>
    <span><img src=”cooking-class.jpg” alt=”cooking class”></span>
    <h4 id=”date”>30/9/2021</h4>
    <h4 id=”day”>Thursday Night</h4>
    <p id=”text”>Come join us for some cooking lessons.</p>
</div>

Once the date is less than Today’s date I would like to create a script that hides that div, so it no longer shows up on the noticeboard.

I have seen a few scripts that remove a by clicking a button as follows:

<button onclick=”remove_click()”>
    Click to remove
</button>

<script type=”text/javascript”>
    function remove_click() {
    var 30-9-21 =
    document.getElementById(“30-9-21”);
    30-9-21.remove();
}
</script>

I would like to automate the process so it happens automatically once the id is less than Today.

CodePudding user response:

You can use the Date.prototype.getTime() feature to compare the current time against the time that the object should be hidden.

If the object still needs to be hidden, you can simply subtract the current time from the time the div should disappear to get the milliseconds the program needs to wait.

// Fetches block
let block = document.getElementById("30-9-21");

// Finds current time
let now = new Date();

// Finds time to hide object
let expire = new Date("9-31-2021");

// If the time to hide the object has already gone by, destroy the div block
if(now.getTime() >= expire.getTime()){
  block.remove();
}else{
  // Otherwise, destroy it when the time to hide the object occurs.
  window.setTimeout(() => {
    block.remove();
  }, expire.getTime() - now.getTime());
}
<div class="image" id="30-9-21" data-name="Thursday">
    <span><img src=”cooking-class.jpg” alt=”cooking class”></span>
    <h4 id="date">30/9/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

CodePudding user response:

Since you are not using a database to query your data, then this is what I would suggest.

  1. Place all your class information into an array of object
  2. Run a for loop to loop through each class
  3. Compare if the date for each class has passed today or your requirement
  4. Add classes that pass your requirements to the DOM

The idea I am trying to show is that if you maintain an array of "classes", you will be able to compare the date and append it to the document only if it fulfills the requirement.

You can test it out below. Feel free to add the alt text or any other ids or classes.

let classArray = [
  {
    date: '9-30-2021',
    day: 'Thursday Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  },
  {
    date: '10-4-2021',
    day: 'Thursday Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  },
  {
    date: '10-10-2021',
    day: 'Thursday Night',
    text: 'Come join us for some cooking lessons',
    image: 'cooking-class.jpg'
  }
];

function generateClass(data) {
  let classContainer = document.createElement("div");
  let date = new Date(data.date);
  classContainer.innerHTML = `
    <span><img src="${data.image}"></span>
    <h4 id="date">${date.getDate()}/${date.getMonth()   1}/${date.getFullYear()}</h4>
    <h4 id="day">${data.day}</h4>
    <p id="text">${data.text}</p>
  `;
  return classContainer;
}

let today = new Date();
for(let i=0; i < classArray.length; i  ) {
  if(new Date(classArray[i].date) > today) {
    document.getElementById('class-list').append(generateClass(classArray[i]));
   }
}
<div id="class-list"></div>

CodePudding user response:

Don't use date in id attribute, use special attribute for this because you may have multiple events with same date (using multiple id with same value is bad practice), so I have used date attribute please check below code.

And if you want to change date format from date-month-year to month/date/year update date format and date divider in htmlDateSettings variable in javascript below.

I have increased one day to event date, if want to hide event which are less than now please remove filteredDate = filteredDate msInOneDay; in javascript below.

I have used two events with different date.

I have filtered date format because javascript need different date format than yours.

Ok now it will automatically hide events which are expired or less than one day from now.

const htmlDateSettings = {
    "date-format": "d-m-y",
    "date-devider": "-"
}

removeExpiredEvents(); // call function automatically

function removeExpiredEvents() {
    let eventItems = Array.from(document.querySelectorAll('.eventItem'));
    let df = htmlDateSettings['date-format'];
    let dd = htmlDateSettings['date-devider'];
    let msInOneDay = 1000 * 60 * 60 * 24;
    let today = new Date().getTime();

    for(let eventItem of eventItems) {
        let date = eventItem.getAttribute('date');
        if(!date) continue;

        date = date.split(dd);
        let dateFormat = df.split(dd);

        let filteredDate = `${date[dateFormat.indexOf('m')]}${dd}${date[dateFormat.indexOf('d')]}${dd}${date[dateFormat.indexOf('y')]}`;
        filteredDate = new Date(filteredDate).getTime();
        filteredDate = filteredDate   msInOneDay; // increased 1 day in event date
        
        if(today > filteredDate) eventItem.style.display = 'none'; 
    }
}
<div class="image eventItem" date="30-9-21" data-name="Thursday">
    <span><img src="cooking-class.jpg" alt="cooking class"></span>
    <h4 id="date">30/9/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

<!-- today event -->
<div class="image eventItem" date="12-10-21" data-name="Thursday">
    <span><img src="cooking-class.jpg" alt="cooking class"></span>
    <h4 id="date">12/10/2021</h4>
    <h4 id="day">Thursday Night</h4>
    <p id="text">Come join us for some cooking lessons.</p>
</div>

CodePudding user response:

<button onclick=”remove_click()”>
    Click to remove
</button>

<script type=”text/javascript”>
    function remove_click() {
       // To remove the element totally from the page
       document.getElementById("30-9-21").innerHTML = "";
       //To just hide the div so you can call it back by making it visible
       document.getElementById("30-9-21").style.display = "none"
    }
</script>

CodePudding user response:

Two things 30-9-21 cant be a variable name the interpreter wont like that so change it to dateDiv or something similar.

The other is that while .remove() will delete the element if your going to add it back later use the hidden attribute.

Also i think you can add the hidden attribute using CSS on click

<script type=”text/javascript”>
    function remove_click() {
    var date =  document.getElementById(“30-9-21”);
    date.hidden = true;
}
</script>
  • Related