What steps can I take to ensure my website is mobile-friendly?

My website isn't displaying correctly on cellphones. According to the tutorial I'm following, it should look like this:

https://i.sstatic.net/XNDfQ.png

However, this is how it appears on my Samsung Galaxy S5:

https://i.sstatic.net/veHTP.png

I suspect that the issue lies within my CSS code. Even though my code matches the instructor's, the rendering of my website differs. Could this be due to different versions of Visual Studio Code?

Here's a snippet of my code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    ... (remaining HTML code)

CSS:

{ 
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'poppins', sans-serif;
}
... (remaining CSS code)

chart.js

Line chart

const ctx = document.getElementById('lineChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: { 
        labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',],
        ... (remaining chart.js code)

doughnut chart

const ctx2 = document.getElementById('doughnut').getContext('2d');
const myChart2 = new Chart(ctx2, {
    type: 'doughnut',
    data: {
        labels: ['Academic', 'Non academic', 'Administration', 'Others'],
        ... (remaining doughnut chart code)

Answer №1

The key to success in this scenario lies in the following actions:

  • To modify CSS, insert canvas { max-width: 100% } within /* charts starts here */
  • In the lineChart JS code, correct the error from responsise: true to responsive: true

By implementing these changes, you can ensure compatibility down to a size of 320x480 in Windows Firefox Responsive Design Mode.

Snippet with corrected code

const ctx = document.getElementById('lineChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',],
        datasets: [{
            label: 'Earnings in $',
            data: [2500,3452,1526,5500,1278,2500,2500,3000,4000,3300,2600,2800],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 3
        }]
    },
    options: {
        responsive: true,
    
    }
});

const ctx2 = document.getElementById('doughnut').getContext('2d');
const myChart2 = new Chart(ctx2, {
    type: 'doughnut',
    data: {
        labels: ['Academic', 'Non academic', 'Administration', 'Others'],
...
        </a>
                </li>
                <li>
                    <a href="#">
                        <i class="fas fa-hand-holding-usd"></i>
                        <div>Earnings</div>
                    </a>
                </li>
                <li>
                    <a href="#">
                        <i class="fas fa-cog"></i>
                        <div>Settings</div>
                    </a>
                </li>
                <li>
                    <a href="#">
                        <i class="fas fa-question"></i>
                        <div>Help</div>
                    </a>
                </li>
            </ul>
        </div>
        <div class="main">
            <div class=...

Answer №2

Resolution

To ensure responsiveness in the provided code, I implemented two adjustments.

1. CSS Modifications

I opted to set the display property of the parent element .charts to block and assigned a margin-bottom of 20px to the .chart canvas container (considering that grid-gap was not an option).

Therefore, around line 207 in style.css, I made the following alteration:

.charts {
  grid-template-columns: 1fr;
}

changed to:

.charts {
  /* grid-template-columns: 1fr; */
  display: block;
}
.chart {
  margin-bottom: 20px;
}

2. JavaScript Adjustments

I encapsulated all your chart setup code within a function called drawChart, which is invoked upon window resizing. Prior to rendering a new chart, any existing chart is first removed to prevent errors. The JavaScript code was adjusted as follows:

let myChart;
let myChart2;

const drawCharts = () => {
  if (myChart) {
    myChart.destroy();
  }
  const ctx = document.getElementById('lineChart').getContext('2d');
  myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',],
      datasets: [{
        label: 'Earnings in $',
        data: [2500, 3452, 1526, 5500, 1278, 2500, 2500, 3000, 4000, 3300, 2600, 2800],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 3
      }]
    },
    options: {
      responsise: true,
    
    }
  });

  if (myChart2) {
    myChart2.destroy();
  }
  const ctx2 = document.getElementById('doughnut').getContext('2d');
  myChart2 = new Chart(ctx2, {
    type: 'doughnut',
    data: {
      labels: ['Academic', 'Non academic', 'Administration', 'Others'],
      datasets: [{
        label: 'Employees',
        data: [42, 12, 8, 6],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      responsive: true
    }
  });
};

drawCharts();

window.onresize = drawCharts;

Elaboration

In identifying potential constraints, I heavily relied on Chrome DevTools, as highlighted by @AHaworth in the comments section.

I concluded that using display: grid; was redundant for smaller screens, prompting me to change the parent element .charts to display: block;.

Furthermore, it appeared that chart.js calculates chart dimensions based on the current parent size. Hence, with window resizing, reconstructing the chart became imperative, leading to the integration of the callback function.

Implement these alterations and assess the outcome against your requirements.

I cannot explain why the original code worked seamlessly for the YouTuber without incorporating the aforementioned changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stuck on AMChart while trying to load data

Hello! I am currently utilizing the AMCharts framework to generate charts from data stored in a MySQL database. However, I have encountered an issue where instead of displaying the chart, I am stuck with a perpetual "Loading Data" message. You can view a ...

Issue with refreshing a material

When updating a transaction, I am encountering the issue of inadvertently deleting other transactions. My goal is to update only one transaction. Can someone review my backend logic to identify the root cause? Schema Details: const mongoose = require(&apo ...

Using an alias to call a function defined in a separate module in TypeScript

The following code snippet is from the v4.js file located inside the uuid folder within Angular's node_modules: var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { ...

Is there a way to identify a location in close proximity to another location?

With a position at (9,-3), I am looking to display all positions surrounding it within a square red boundary. However, I am struggling to find the algorithm to accomplish this task. Any help or alternative solutions would be greatly appreciated. Thank you ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Unlocking the potential of NextAuth.js by enhancing the user session with additional database information on authentication

Currently, I am in the process of creating a straightforward credentials sign flow using next-auth ^4.24.5 with a nextjs 14 app. Within my user model, there is a boolean property named 'isAdmin' that I wish to make accessible in my session using ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

Obtain HTML element from a text snippet

What is the most efficient method for extracting an HTML tag from a string? I am dealing with a string of HTML that includes multiple embed tags containing videos. The number of embed tags in the string can vary. I understand that I could use the followi ...

What is the best way to include a drop-right menu within a dropdown menu?

Hey there! I'm working on a page that features a dropdown navbar. My goal is to create a secondary dropdown that appears to the right when hovering over an li element within the initial dropdown. Any tips on how to accomplish this? Thanks in advance! ...

Issues with routing in Angular's ui-router when using the href attribute

I created a state and am attempting to navigate to another page. Despite no console errors, the navigation is not functioning as expected. index.html <body ng-app="app"> <a href='#/first-msg'>link</a> <div ui-view&g ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Input a new function

Trying to properly type this incoming function prop in a React Hook Component. Currently, I have just used any which is not ideal as I am still learning TypeScript: const FeaturedCompanies = (findFeaturedCompanies: any) => { ... } This is the plain fun ...

Enhancing the Search Form Minimum Width in Bootstrap 4 Navbar

Looking for a way to create a search form with a width of 100% and a minimum width within a Bootstrap 4 navbar? Check out my code snippet here. <nav class="navbar navbar-expand-md navbar-light bg-faded"> <a href="/" class="navbar-brand">Brand& ...

Eliminate the array from the data retrieved through an http request in AngularJS

Currently, I am making an http call to retrieve data from a database. This process involves calling 6 different types individually. $scope.getAll = function() { var url = 'http://someurl/'; var allObjects = []; $sc ...

Minimizing the frequency of getElementById calls for the same HTML element

When dealing with repetitive function calls using the same element as a parameter, is it more effective to store the element as a global variable? For instance, imagine a function that is triggered on every key press and takes an element as an argument. ...

Halt the jQueryUI Slider once a specific difference or margin has been reached

I have a specific margin or distance that needs to be changed from an HTML select option tag dynamically in the future. I have implemented a Range Slider using jQueryUI Slider. My objective: I am looking to halt the sliding action once a specific distance ...

Injecting an attribute with the forbidden character "@" into the Document Object Model (DOM

Scenario I find myself needing to update some existing HTML using JavaScript, but I'm limited in that the server side is out of my control. This means that any changes must be made client-side only without altering the original HTML document. To acc ...

When cycling through an array in ReactJS, HTML tags are not displayed or processed

I'm diving into the world of ReactJS and trying to grasp the fundamental concepts. To pros out there, my question might seem like a beginner's query ;) Here's the component I am working on: import React from "react"; function Nam ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

jquery unclean data, in need of the jquery ui popup dialog

I have been experimenting with this library to determine if a form is dirty. By default, it triggers the standard browser confirmation asking whether you are certain about navigating away from the page. The jquery dirtyforms website includes a section sugg ...