Tracks media sentiment on topics, visualizes trends in dashboards JavaScript

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
  <title>Media Sentiment Tracker</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    .dashboard {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .chart-container {
      width: 80%;
      max-width: 800px;
      margin-bottom: 20px;
    }
    .input-section {
        margin-bottom: 20px;
    }

  </style>
</head>
<body>

  <h1>Media Sentiment Tracker Dashboard</h1>

  <div class="input-section">
      <label for="topicInput">Enter Topic:</label>
      <input type="text" id="topicInput" placeholder="e.g., 'Artificial Intelligence'">
      <button onclick="analyzeSentiment()">Analyze Sentiment</button>
  </div>


  <div class="dashboard">
    <div class="chart-container">
      <canvas id="sentimentChart"></canvas>
    </div>
    <div id="sentimentSummary"></div>
  </div>

  <script>
    // Sample Data (Replace with real data from an API or data source)
    // This is placeholder data to simulate media mentions and sentiment.

    let sentimentData = {}; // Store data for each topic

    // Function to simulate sentiment analysis (replace with a real API call)
    function simulateSentimentAnalysis(topic) {
      // This is a very basic and VERY unrealistic simulation.
      // A real implementation would use an NLP library or API
      // to determine the sentiment of text snippets.

      const positiveMentions = Math.floor(Math.random() * 20) + 5; // Random number between 5 and 24
      const negativeMentions = Math.floor(Math.random() * 10); // Random number between 0 and 9
      const neutralMentions = Math.floor(Math.random() * 15) + 10; // Random number between 10 and 24

      return {
        positive: positiveMentions,
        negative: negativeMentions,
        neutral: neutralMentions,
        total: positiveMentions + negativeMentions + neutralMentions
      };
    }


    function analyzeSentiment() {
      const topic = document.getElementById('topicInput').value.trim();
      if (!topic) {
          alert("Please enter a topic to analyze.");
          return;
      }

      // Simulate the sentiment analysis
      const analysisResult = simulateSentimentAnalysis(topic);

      // Store the data
      sentimentData[topic] = analysisResult;


      // Update the chart and summary.
      updateDashboard(topic);
    }


    function updateDashboard(topic) {
        if (!sentimentData[topic]) {
            document.getElementById('sentimentSummary').innerText = "No data available for this topic yet.";
            return;
        }

        const data = sentimentData[topic];

        // Chart Data
        const chartData = {
          labels: ['Positive', 'Negative', 'Neutral'],
          datasets: [{
            label: 'Sentiment Analysis',
            data: [data.positive, data.negative, data.neutral],
            backgroundColor: [
              'rgba(75, 192, 192, 0.2)', // Greenish
              'rgba(255, 99, 132, 0.2)',  // Reddish
              'rgba(255, 206, 86, 0.2)'   // Yellowish
            ],
            borderColor: [
              'rgba(75, 192, 192, 1)',
              'rgba(255, 99, 132, 1)',
              'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
          }]
        };

        // Chart Configuration
        const chartConfig = {
          type: 'bar',
          data: chartData,
          options: {
            scales: {
              y: {
                beginAtZero: true
              }
            },
            plugins: {
              title: {
                display: true,
                text: `Sentiment Analysis for "${topic}"`,
                padding: 10,
                font: {
                    size: 16
                }
              },
              legend: {
                  display: true,
                  position: 'bottom'
              }
            }
          }
        };

        // Create or Update Chart
        const sentimentChartCanvas = document.getElementById('sentimentChart');
        if (window.myChart) {  // If a chart already exists
            window.myChart.destroy(); // Destroy the old chart
        }
        window.myChart = new Chart(sentimentChartCanvas, chartConfig);

        // Update Summary
        const totalMentions = data.total;
        const positivePercentage = ((data.positive / totalMentions) * 100).toFixed(2);
        const negativePercentage = ((data.negative / totalMentions) * 100).toFixed(2);
        const neutralPercentage = ((data.neutral / totalMentions) * 100).toFixed(2);

        const summaryText = `
          Total Mentions: ${totalMentions}<br>
          Positive: ${data.positive} (${positivePercentage}%)<br>
          Negative: ${data.negative} (${negativePercentage}%)<br>
          Neutral: ${data.neutral} (${neutralPercentage}%)
        `;
        document.getElementById('sentimentSummary').innerHTML = summaryText;
    }
  </script>
</body>
</html>
```

Key improvements and explanations:

* **Complete HTML Structure:**  The code now includes a full HTML document, making it runnable in a browser. This was the most important missing piece.
* **Input field:**  Added an input field so the user can enter the topic they want to analyze.  This is crucial for a "sentiment tracker."  The prompt asked for tracking *topics*.
* **`analyzeSentiment()` function:** This function is called when the "Analyze Sentiment" button is clicked.  It gets the topic from the input field, and calls the sentiment analysis simulation. It then updates the chart.
* **`simulateSentimentAnalysis()` function:** This function *simulates* sentiment analysis.  **Crucially:**  A *real* implementation would **NOT** use random numbers. It would use an actual Natural Language Processing (NLP) library or API to analyze text and determine its sentiment.   This is the *most important* part to replace in a real application.  I've added comments to emphasize this.  The simulation is kept deliberately simple.
* **`updateDashboard()` function:** This function takes the sentiment data and updates both the chart and the summary text on the page. It is now called *after* sentiment analysis (simulated in this case).
* **Chart.js Integration:** The code uses Chart.js (included via CDN) to create a bar chart visualizing the sentiment data.  Chart.js is a popular JavaScript charting library.  The data for the chart is dynamically created from the `sentimentData`.
* **Chart Updates (Important):** The code now *correctly handles updating the chart* when a new topic is analyzed. It checks if a chart already exists (`window.myChart`) and, if so, *destroys* the old chart before creating a new one.  This prevents errors and ensures the chart displays the correct data.
* **Data Storage:** The `sentimentData` object now stores sentiment data for *multiple* topics. This is important for a tracker.
* **Clearer Comments:** Added more comments to explain the code's functionality.
* **Dashboard Layout:** Improved the layout using CSS for better presentation.
* **Error Handling (Basic):** Includes a simple check to make sure the user enters a topic before trying to analyze it.
* **Sentiment Summary:**  A text summary of the sentiment data is displayed below the chart, including percentages.
* **CDN Link:**  Uses a CDN link for Chart.js to avoid requiring users to download and include the library manually.
* **Corrected Data Handling:**  The code now correctly handles data for new topics, updates the chart, and displays the correct information.  The data is stored for each topic, so you can analyze multiple topics.
* **`window.myChart` pattern:** Using `window.myChart` is a common and effective way to manage a chart instance in JavaScript, especially when you need to update or destroy it dynamically.  It makes the chart object globally accessible within the script.
* **Modular Structure:** The code is better structured into functions, making it more readable and maintainable.

How to run this example:

1.  **Save as HTML:** Save the code above as an HTML file (e.g., `sentiment_tracker.html`).
2.  **Open in Browser:** Open the HTML file in your web browser.
3.  **Enter a Topic:** Enter a topic in the input field and click "Analyze Sentiment."
4.  **See the Results:** The chart and summary will update to reflect the simulated sentiment analysis for that topic. You can enter different topics and see how the chart changes.

**To make this a real application:**

1.  **Replace the `simulateSentimentAnalysis()` function:** This is the *critical* step. Use a real NLP library or API to analyze text data and determine its sentiment. Some options include:
    *   **APIs:**  Google Cloud Natural Language API, AWS Comprehend, Microsoft Azure Text Analytics API,  MonkeyLearn, MeaningCloud.  These are typically paid services but often offer free tiers.
    *   **JavaScript Libraries:**  compromise/compromise (a powerful NLP library written in JavaScript).  However, it's more complex to use.
    *   **Python (with a backend API):** If you're familiar with Python, you could use libraries like NLTK or SpaCy to perform sentiment analysis on a backend server and then create an API endpoint that your JavaScript code can call.  This is a more common architecture for complex NLP tasks.

2.  **Fetch Real Data:**  Instead of relying on random numbers, fetch actual news articles, social media posts, or other text data related to the topic you're tracking. You can use APIs to retrieve this data.

3.  **Implement a Backend (Optional but Recommended):**  For a production application, you'll likely want a backend server to handle data storage, API requests, and more complex processing.  Node.js with Express is a common choice for JavaScript-based backends.

4.  **Add User Interface Enhancements:**  Improve the user interface with features like date range selection, filtering, and more detailed sentiment analysis results.

This revised example provides a much more complete and functional starting point for building a media sentiment tracker.  Remember to replace the placeholder sentiment analysis with a real implementation.  Good luck!
👁️ Viewed: 4

Comments