Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday 28 November 2023

Revisit "How to make the entire page fade in on load" using Vue.js

 index.html

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Body Fade In</title>

    <link rel="stylesheet" href="./style.css" />

  </head>

  <body>

    <transition name="fade" appear>

      <h1>Hello World!</h1>

    </transition>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <script src="./app.js"></script>

  </body>

</html>

style.css

.fade-enter-active,

.fade-leave-active {

  transition: opacity 1s;

}

.fade-enter-from,

.fade-leave-to {

  opacity: 0;

}

app.js

const app = Vue.createApp({});

app.mount("body");

Revisit "Simple tab navigation using jQuery" using Vue.js

This is the first of a series in which I revisit old blog posts which made use of JavaScript and jQuery. I attempt to implement them, this time using Vue.js in order to improve my Vue.js skills.
First up is one from 2010 titled Simple tab navigation using jQuery.

index.html
<html lang="en">
  <head>
    <meta charset="UTF-8"></meta>
    <title>Tabbed Navigation</title>
    <style type="text/css">
      body {
        font-family: Sans-serif;
      }
      #subSystem {
        margin: 0 auto;
        width: 400px;
      }
      #subNav a.subMenu {
        display: block;
        text-decoration: none;
        float: left;
        text-align: center;
        width: 5rem;
        height: 2.5rem;
        padding-top: 1rem;
        border-top: 0.0625rem solid #ccc;
        border-left: 0.0625rem solid #ccc;
        border-right: 0.0625rem solid #ccc;
        color: #000;
      }
      #subNav a.subMenu:hover {
        background: #a3a3a3;
        color: #fff;
      }
      .menuSelected {
        background: #ccc;
        color: #fff;
      }
      #subContent {
        clear: left;
        min-height: 25rem;
        height: 25rem;
        border: 0.0625rem solid #ccc;
      }
    </style>
  </head>
  <body>
    <div id="subSystem">
      <div id="subNav">
        <a class="subMenu menuSelected" click="loadContent" href="./subPage1.html">First</a>
        <a class="subMenu" click="loadContent" href="./subPage2.html">Second</a>
        <a class="subMenu" click="loadContent" href="./subPage3.html">Third</a>
      </div>
      <div id="subContent"></div>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="./app.js"></script>
  </body>
</html>

app.js

const app = Vue.createApp({
  methods: {
    loadContent(event) {
      event.preventDefault();
      const href = event.target.getAttribute("href");
      fetch(href)
        .then((response) => response.text())
        .then((data) => {
          document.getElementById("subContent").innerHTML = data;
        })
        .catch((error) => {
          console.error("Error loading content:", error);
        });
    },
  },
  mounted() {
    // Simulate a click on the first tab when the page loads
    const firstTab = document.querySelector(".subMenu.menuSelected");
    if (firstTab) {
      firstTab.click();
    }
  },
});

app.mount("#subSystem");

Tuesday 18 April 2023

JavaScript fetch, VS Code, CORS, Debugging and curl

I've recently been trying to use the Pocket API to bring my favourite links into a page. Naturally, I was starting from a position of testing it on localhost. I've also been using VS Codium, which has improved on Ubuntu. I use the Brave browser and so was looking to make use of this in my debugging.

So first things, first I needed to get debugging happening in VS Codium using Brave on Ubuntu. As you try and run the debugger, you have the option to create a launch.json file for your project. Here, I selected to create a Chrome web app. Once the launch.json was created, I edited it with the following, in order that the debugger used Brave:

{

    "version": "0.2.0",

    "configurations": [

        {

            "type": "chrome",

            "request": "launch",

            "name": "Brave",

            "runtimeExecutable": "/opt/brave.com/brave/brave-browser",

            "userDataDir": true,

            "url": "http://localhost:5500",

            "webRoot": "${workspaceFolder}",

            "runtimeArgs": ["--disable-web-security"]

        }

    ]

}

I the setting "--disable-web-security" fixed the CORS problem commonly faced such as,

Access to fetch at ‘http://localhost:8000/api/v1/messages’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The final issue I encountered was the code itself. I'd successfully retrieved the data I was looking for using curl, but converting the curl command to a JavaScript fetch was problematic. I then came across this page which helped.

Now we're cooking!


Wednesday 10 April 2019

Thursday 7 March 2019

Using the Vanilla JS Component template with LAMP

I use the Vanilla JS Component at https://github.com/guitarbeerchocolate/vanilla-js-component, and you have LAMP server on my box. However, when I want to call PHP scripts which are on the LAMP server such as, in a POST request using fetch or XHR within JavaScript I get the following errors in my browser:
Access to XMLHttpRequest at 'http://localhost/test/vanilla-js-POST-JSON/login.php' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

postjson_xhr.js:19 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost/test/vanilla-js-POST-JSON/login.php with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Obviously, it's treating the LAMP server like another domain.

The way to fix this is to put a line at the top of your PHP script thus:
header('Access-Control-Allow-Origin: *');
Happy coding.

Tuesday 26 February 2019

Vanilla JavaScript Login form POST handler using XHR

I did a similar post to this called Vanilla JavaScript Login form POST handler using fetch. Fetch returns a JavaScript Promise, which can be a bit of a pain so I've also done a version using XHR, see below:

var postJSON = function(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send(data);
};

Here's how to call it:
const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  postJSON(url, method, new FormData(form), function(error, json) {
    if (error !== null) {
      console.log('parsing failed', error);
    } else {
      console.log('json.username', json.username);
      console.log('json.password', json.password);
    }
  });
});

Tuesday 12 February 2019

Vanilla JS Bind

I have created a Vanilla JavaScript bind class. This has been built using https://github.com/guitarbeerchocolate/vanilla-js-component and resides at https://github.com/guitarbeerchocolate/JS_Bind
It employs :


  • HTML5
  • ES6

Vanilla JS carousel

I have created a Vanilla JavaScript carousel. This has been built using https://github.com/guitarbeerchocolate/vanilla-js-component and resides at https://github.com/guitarbeerchocolate/vanilla-js-carousel
It employs :

  • HTML5
  • SASS
  • BEM
  • ES6

Vanilla JS component

I'm creating a number of elements using Vanilla JavaScript. They will use :

  • HTML5
  • SASS
  • CSS grid
  • BEM
  • Media queries
  • ES6

In order to put these elements together more efficiently, I have put together a small framework, from which I will fork.
It lies at https://github.com/guitarbeerchocolate/vanilla-js-component

Wednesday 6 February 2019

Vanilla JavaScript Login form POST handler using fetch

I've been updating my gists lately because I'm now in position to leave jQuery behind. See https://gist.github.com/guitarbeerchocolate
So, here's how to pass login form data to some middleware and accept JSON in return using fetch.

const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  fetch(url, {
    method: method,
    body: new FormData(form)
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('json.username', json.username)
    console.log('json.password', json.password)
  }).catch(function(error) {
    console.log('parsing failed', error)
  })
});

Wednesday 23 May 2018

The 2018 Web Developer : Installing webpack

webpack is a node module which allows us to package source files into a single bundle to cut down on the number of HTTP requests.
I'm going to assume we have a directory called 'myApp' and an index.html
cd myApp
npm init -y
This will create a package.json file.
Within package.json, add some text to the "description" field to avoid a warning at the next stage.
If you're not going to use git at this stage also within package.json, add the line "private": true,
Again this is to avoid warnings.
Now we're ready to take node modules.
npm install webpack webpack-cli --save-dev
Now we create a file for configuring webpack.
touch webpack.config.js
Now let's create a directory structure for our source.
mkdir src
cd src
mkdir js
mkdir css
cd js
touch output.js
Now let's add some code to output.js and save.
console.log('Hello world!');
Now let's go back to the myApp directory.
cd ../..
Now we can edit the webpack.config.js file.
Add the following content to webpack.config.js and save.
const path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/js/output.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
}
You can see from the code above a number of things:

  • A 'path' constant to be used to establish where to get files from.
  • A module.exports object.
  • The mode in which we're working.
  • 'entry' is the start location that webpack will look to find the things it need to bundle.
  • 'output' is the location of the bundle.

So our HTML file, index.html will look like this:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Webpack</title>
  </head>
  <body>    
    <script src="./dist/bundle.js"></script>
  </body>
</html>
Now it's time to run webpack
From the command line, and in the 'myApp' directory type:
webpack
The result should be a directory called 'dist', which contains a file called bundle.js.
When loading the page, if we look at the console. It should say 'Hello world!'.

Monday 14 May 2018

Get blogspot content using JavaScript fetch

This example pulls in JSON data from a blog hosted on blogspot.com

First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

const fetch = require('node-fetch');
const url = 'http://some-website.blogspot.com/feeds/posts/default/-/blog?alt=json';
var myFetch = fetch(url);

myFetch.then(response => response.json()).then(function(data) {
  showMyData(data);
}).catch(function(err)
{
  console.log('Caught an error ',err);
});

function showMyData(md) {
  md.feed.entry.forEach((e) => {
    var title = (e.title.$t || '');
var url = (e.link || []).pop().href;
    var date = new Date(e.updated.$t || Date.now());
    var lessLines = e.content.$t.substr(0, 800);
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var theMonth = months[date.getMonth()];
    var theYear = date.getFullYear();
  });
}

Friday 11 May 2018

The 2018 Web Developer : JavaScript JSON processing without jQuery

Enter 'fetch'. The JavaScript API which performs HTTP requests.
First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

In this example, I have a simple .json file which contains a set of URLs and their types.

const fetch = require('node-fetch');
const url = 'feeds.json';
var myFetch = fetch(url);

myFetch.then(response=>response.json()).then(function(data) {
    showMyData(data);
  });

function showMyData(md)
{
  md.forEach((value) => {
    console.log(value.URL, value.TYPE);
  });
}

Thursday 10 May 2018

The 2018 Web Developer : Animating without jQuery

There's not much wrong with jQuery other than it's size. Sometimes when you want to keep your website very lean you may wish to rely on pure JavaScript. In this case, I use the excellent animate.css. Even better than that, you can use animate.scss.
To add it to your project, change to your project directory:
cd myApp/git
Then use the following command:
git clone https://github.com/geoffgraham/animate.scss
Here is an example page which, on page load brings in animate.css and runs the function doTheSlide, to animate the contents of the H1 tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Do the slide</title>
<link rel="stylesheet" href="scss/custom.css" />
</head>
<body>
  <h1>Hello world!</h1>
</body>
</html>
Nothing happens until you create your scss file. custom.css is created thus:
cd myApp/scss
node-sass -w custom.scss custom.css
Now let's put some clever stuff in the custom.scss file.
@import "../git/animate.scss/animate.scss";
h1 {
  @include slideInLeft();
}
Refresh the browser and, hey presto! Now we're animating.

The 2018 Web Developer : Adding and using babel

Babel is a JavaScript compiler. It allows you to use modern JavaScript, then compiles it to a file which will work in all browsers.
To install it, use :
npm install -g babel-cli
To run it, change to the directory containing your JavaScript:
cd myApp
Then run a command like this:
npx babel custom.js -w -o script.js
custom.js is the file you are editing ans script.js is your output file. If you are using the -w (watch) parameter as above, the compilation will take place each time you save custom.js.