Satyajit Roy
Satyajit Roy

Reputation: 547

Why adding style through JavaScript is not working

I am a beginner and I am learning JavaScript now. I am trying to make a javascript project. On this project, I am trying to add a style through javascript. On my project, there is a button (anchor tag) named "Close". When it will click, the style text-decoration: line-through will be added to the description which id is issue-{id}. But the style is not working. The style is not added when I am clicking on the close button.

Look at the javascript code on line no 29 and 53.

Here is my full code:

document.getElementById('issueInputForm').addEventListener('submit', submitIssue);

let issueCounterEl = document.getElementById("issue-counter");

function submitIssue(e) {
    const getInputValue = id => document.getElementById(id).value;
    const description = getInputValue('issueDescription');
    const severity = getInputValue('issueSeverity');
    const assignedTo = getInputValue('issueAssignedTo');
    const id = Math.floor(Math.random() * 100000000) + '';
    const status = 'Open';
    const issue = { id, description, severity, assignedTo, status };
    let issues = [];
    if (localStorage.getItem('issues')) {
        issues = JSON.parse(localStorage.getItem('issues'));
    }
    issues.push(issue);
    localStorage.setItem('issues', JSON.stringify(issues));
    document.getElementById('issueInputForm').reset();
    fetchIssues();
    e.preventDefault();
}

const closeIssue = id => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const currentIssue = issues.find(issue => issue.id == id);
    currentIssue.status = 'Closed';
    
    document.getElementById(`issue-${id}`).style.textDecoration = 'line-through'; // This line - line: 29. Id form line: 53

    localStorage.setItem('issues', JSON.stringify(issues));
    fetchIssues();
}

const deleteIssue = id => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const remainingIssues = issues.filter(issue => issue.id != id)
    localStorage.setItem('issues', JSON.stringify(remainingIssues));
    fetchIssues();
}

const fetchIssues = () => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const issuesList = document.getElementById('issuesList');
    issuesList.innerHTML = '';

    for (var i = 0; i < issues.length; i++) {
        const { id, description, severity, assignedTo, status } = issues[i];

        issuesList.innerHTML += `<div class="well">
                              <h6>Issue ID: ${id} </h6>
                              <p><span class="label label-info"> ${status} </span></p>
                              <h3 id="issue-${id}"> ${description} </h3> 
                              <p><span class="glyphicon glyphicon-time"></span> ${severity}</p>
                              <p><span class="glyphicon glyphicon-user"></span> ${assignedTo}</p>
                              <a href="#" onclick="closeIssue(${id})" class="btn btn-warning">Close</a>
                              <a href="#" onclick="deleteIssue(${id})" class="btn btn-danger">Delete</a>
                              </div>`;
    }
    issueCounterEl.innerText = issues.length;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Issue Tracker: </title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body onload="fetchIssues()">
    <div class="container">
        <h1>Issue Tracker: <span id="issue-counter"></span></h1>
        <div class="jumbotron">
            <h3>Add New Issue:</h3>
            <form id="issueInputForm">
                <div class="form-group">
                    <label for="issueDescription">Description</label>
                    <input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
                </div>
                <div class="form-group">
                    <label for="issueSeverity">Severity</label>
                    <select id="issueSeverity" class="form-control">
                        <option value="Low">Low</option>
                        <option value="Medium">Medium</option>
                        <option value="High">High</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="issueAssignedTo">Assigned To</label>
                    <input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
                </div>
                <button type="submit" class="btn btn-primary">Add</button>
            </form>
        </div>
        <div class="col-lg-12">
            <div id="issuesList"></div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <script src="main.js"></script>
</body>

</html>

There is no warning or error in the chrome dev tools.

How can I solve the problem?

Upvotes: 3

Views: 3398

Answers (6)

user13899130
user13899130

Reputation:

Your code is all-right but has a small mistake. All you need to do is just put the line document.getElementById(`issue-${id}`).style.textDecoration = 'line-through'; after fetchIssues();.

Then it will look like this:

const closeIssue = id => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const currentIssue = issues.find(issue => issue.id == id);
    currentIssue.status = 'Closed';
    localStorage.setItem('issues', JSON.stringify(issues));
    fetchIssues();
    document.getElementById(`issue-${id}`).style.textDecoration = "line-through";
}

Upvotes: 1

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13978

You can't see the strike through effect in UI because you are always display the information from the local storage setup. You are not updating the strike through style effect on your local storage information. So before fetching your information update your local storage information for the specific id with the strike through style effect like below.

Instead of

document.getElementById(`issue-${id}`).style.textDecoration = 'line-through'; // This line - line: 29. Id form line: 53

Use below

issues.find(issue => issue.id == id).style.textDecoration = 'line-through';

The above line will update the local storage value and you can see the effect in UI.

document.getElementById('issueInputForm').addEventListener('submit', submitIssue);

let issueCounterEl = document.getElementById("issue-counter");

function submitIssue(e) {
    const getInputValue = id => document.getElementById(id).value;
    const description = getInputValue('issueDescription');
    const severity = getInputValue('issueSeverity');
    const assignedTo = getInputValue('issueAssignedTo');
    const id = Math.floor(Math.random() * 100000000) + '';
    const status = 'Open';
    const issue = { id, description, severity, assignedTo, status };
    let issues = [];
    if (localStorage.getItem('issues')) {
        issues = JSON.parse(localStorage.getItem('issues'));
    }
    issues.push(issue);
    localStorage.setItem('issues', JSON.stringify(issues));
    document.getElementById('issueInputForm').reset();
    fetchIssues();
    e.preventDefault();
}

const closeIssue = id => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const currentIssue = issues.find(issue => issue.id == id);
    currentIssue.status = 'Closed';    
    issues.find(issue => issue.id == id).style.textDecoration = 'line-through';

    localStorage.setItem('issues', JSON.stringify(issues));
    fetchIssues();
}

const deleteIssue = id => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const remainingIssues = issues.filter(issue => issue.id != id)
    localStorage.setItem('issues', JSON.stringify(remainingIssues));
   fetchIssues();
}

const fetchIssues = () => {
    const issues = JSON.parse(localStorage.getItem('issues'));
    const issuesList = document.getElementById('issuesList');
    issuesList.innerHTML = '';

    for (var i = 0; i < issues.length; i++) {
        const { id, description, severity, assignedTo, status } = issues[i];

        issuesList.innerHTML += `<div class="well">
                              <h6>Issue ID: ${id} </h6>
                              <p><span class="label label-info"> ${status} </span></p>
                              <h3 id="issue-${id}"> ${description} </h3> 
                              <p><span class="glyphicon glyphicon-time"></span> ${severity}</p>
                              <p><span class="glyphicon glyphicon-user"></span> ${assignedTo}</p>
                              <a href="#" onclick="closeIssue(${id})" class="btn btn-warning">Close</a>
                              <a href="#" onclick="deleteIssue(${id})" class="btn btn-danger">Delete</a>
                              </div>`;
    }
    issueCounterEl.innerText = issues.length;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Issue Tracker: </title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body onload="fetchIssues()">
    <div class="container">
        <h1>Issue Tracker: <span id="issue-counter"></span></h1>
        <div class="jumbotron">
            <h3>Add New Issue:</h3>
            <form id="issueInputForm">
                <div class="form-group">
                    <label for="issueDescription">Description</label>
                    <input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
                </div>
                <div class="form-group">
                    <label for="issueSeverity">Severity</label>
                    <select id="issueSeverity" class="form-control">
                        <option value="Low">Low</option>
                        <option value="Medium">Medium</option>
                        <option value="High">High</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="issueAssignedTo">Assigned To</label>
                    <input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
                </div>
                <button type="submit" class="btn btn-primary">Add</button>
            </form>
        </div>
        <div class="col-lg-12">
            <div id="issuesList"></div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <script src="main.js"></script>
</body>

</html>

Upvotes: 1

huan feng
huan feng

Reputation: 8623

  1. This is because you add the id on the wrong element, it should on <h6> and you put it on <h3>.
  2. Comment your fetch method, because it will override the style you just applied.

See fiddle: https://jsfiddle.net/ramseyfeng/41kvwqye/

issuesList.innerHTML += `<div class="well">
                              <h6 id="issue-${id}">Issue ID: ${id} </h6>
                              <p><span class="label label-info"> ${status} </span></p>
                              <h3> ${description} </h3> 
                              <p><span class="glyphicon glyphicon-time"></span> ${severity}</p>
                              <p><span class="glyphicon glyphicon-user"></span> ${assignedTo}</p>
                              <a href="#" onclick="closeIssue(${id})" class="btn btn-warning">Close</a>
                              <a href="#" onclick="deleteIssue(${id})" class="btn btn-danger">Delete</a>
                              </div>`;

Upvotes: 1

sooraj s pillai
sooraj s pillai

Reputation: 916

Try this

document.getElementById(`issue-${id}`).style.textDecoration = "line-through"; 

Upvotes: 0

Matthias
Matthias

Reputation: 180

Just a little tip: (not going to solve your problem) Set another variable as the element:

issueid = document.getElementById(`issue-${id}`)

Then, do the following:

issueid.style.textDecoration = 'line-through';

(I know this should be in the comments but I don't have enough rep.)

Upvotes: 0

user16730065
user16730065

Reputation:

Your JavaScript runs before your done is rendered, so you need to wait for it to finished and you do that with

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
/// add code here
});

Upvotes: 0

Related Questions