How can we help you today?

How to Insert JavaScript Code into SharePoint Using the ShortPoint Code Editor Web Part

The ShortPoint Code Editor Web Part allows you to inject Javascript code into your Modern SharePoint page. This article provides detailed instructions for implementation. We offer both a Quick Walkthrough for users familiar with the free web part and a comprehensive step-by-step tutorial for those who need more details.


TABLE OF CONTENTS


Prerequisites

  • Ensure the ShortPoint Code Editor Web Part is installed on your SharePoint site. For installation instructions, read our article on How to Install ShortPoint Code Editor in SharePoint.
  • You have the proper SharePoint permissions to edit the target Modern SharePoint page.

Quick Walkthrough

  1. Get custom Javascript code.
  2. Navigate to the SharePoint page and click Edit.
  3. Click Add new web part in the location where you want to insert your HTML code.
  4. Search for ShortPoint Code in the web parts library and select it.
  5. Edit the default placeholder content properties.
  6. Paste your Javascript code into the Javascript field.
  7. Make any needed adjustments to the code and web part settings.
  8. Republish the page.

Step-by-Step Tutorial

You can obtain custom Javascript code from various sources to enhance your SharePoint page functionality. The following detailed steps will guide you through how to implement them on your page:

Step 1: Prepare your custom Javascript

Obtain or write the Javascript code for your desired page functionality. For this demonstration, we'll use a sample script that displays fireworks animations when users visit the page on their birthday. We'll show you how to add this code to your Modern SharePoint page.


birthday JavaScript result


Here are the custom codes that we will use:

  • CSS Code
.birthday-banner {
  display: none;
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: linear-gradient(45deg, #ff6b6b, #ff8e53);
  color: white;
  padding: 20px 40px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
  text-align: center;
  font-family: Arial, sans-serif;
  z-index: 1000;
  animation: slideDown 0.5s ease-out;
}

@keyframes slideDown {
  from { top: -100px; opacity: 0; }
  to { top: 20px; opacity: 1; }
}

.firework {
  position: absolute;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  animation: explode 1s ease-out forwards;
}

@keyframes explode {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(30);
    opacity: 0;
  }
}
  • JavaScript code - this code checks for the user's birthday and launches fireworks animations
/* Uncomment the next line to test the fireworks effect */
// showBirthdayBanner();

const getUserBirthday = async () => {
    try {
        // Get the user profile properties using SharePoint REST API
        const response = await fetch(`${_spPageContextInfo.webAbsoluteUrl}/_api/SP.UserProfiles.PeopleManager/GetMyProperties`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json;odata=verbose',
                'Content-Type': 'application/json;odata=verbose'
            },
            credentials: 'include'
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // Find the birthday property in the user profile
        const birthdayProperty = data.d.UserProfileProperties.results.find(prop => prop.Key === "SPS-Birthday");

        if (birthdayProperty) {
            const birthday = new Date(birthdayProperty.Value);
            return birthday;
        } else {
            console.log("Birthday not found in user profile");
            return null;
        }
    } catch (error) {
        console.error("Error fetching user birthday:", error);
        throw error;
    }
};

getUserBirthday().then(birthday => {
    if (birthday) {
        console.log("User's birthday:", birthday.toLocaleDateString());
        console.log(birthday);
        window.userBirthday = birthday;

        // Example output: "User's birthday: 1/1/1990"

        checkBirthday();
    }
}).catch(error => {
    console.error("Failed to get birthday:", error);
});

function checkBirthday() {
    const today = new Date();
    const birthday = new Date(window.userBirthday);

    // Check if today matches birthday (month and day only) - show banner only once
    if (today.getMonth() === birthday.getMonth() &&
        today.getDate() === birthday.getDate() &&
        window.localStorage.getItem("showedBirthdayBanner") != "1") {
        window.localStorage.setItem("showedBirthdayBanner", "1");
        showBirthdayBanner();
    }
}

function showBirthdayBanner() {
    const banner = document.createElement('div');
    banner.className = 'birthday-banner';
    banner.innerHTML = `Happy birthday ${window._spPageContextInfo?.userDisplayName?.split(" ")[0]}! Wish you an awesome year ahead!`;
    document.body.appendChild(banner);
    banner.style.display = 'block';
    // Create fireworks
    createFireworks();
    setTimeout(function() {
        banner.remove();
    }, 6000)
}

function createFireworks() {
    const colors = ['#ff0', '#f0f', '#0ff', '#f00', '#0f0'];
    for (let i = 0; i < 50; i++) {
        setTimeout(() => {
            const firework = document.createElement('div');

            firework.className = 'firework';
            firework.style.left = Math.random() * window.innerWidth + 'px';
            firework.style.top = Math.random() * window.innerHeight + 'px';
            firework.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
            document.body.appendChild(firework);

            // Remove firework element after animation
            setTimeout(() => firework.remove(), 1000);
        }, Math.random() * 2000);
    }
}

Step 2: Enter SharePoint page edit mode

  • Open the SharePoint page where you want the event to happen.
  • Press the Edit button.


edit sharepoint page

  • Close the SharePoint Toolbox.

close toolbox


Step 3: Insert ShortPoint Code Web Part

  • Click the + Add new web part icon.


add new web part


  • In the web parts library, search for ShortPoint Code and select it.


select shortpoint code


Placeholder content will be added to the page.


placeholder content


Step 4: Paste Javascript and customize settings

  • Press the Edit properties icon. This will open the editing interface of the ShortPoint Code Editor Web Part.
  • Copy the CSS code provided in Step 1 and replace the default content in the CSS field. (Note: This CSS step applies specifically to our example. Your implementation may not require custom CSS code.)
  • Hit Save.
  • Copy the JavaScript code provided in Step 1, replace the default content in the JavaScript field, and save.
  • Remove the default content in the HTML field and save.


paste JavaScript code



Step 5: Hit Republish

Now that you have finished configuring the Code web part, Republish the page. Your users will then be able to see the JavaScript code's effects, in our example, on their birthdays.


That's it! You can now use JavaScript code to enhance your user's intranet experience and add other dynamic features.


Related articles:



Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.

World's best intranet sites are designed using ShortPoint

Get started today! Learn more
See all 18 topics

Start a trial

Ignite your vision. Install ShortPoint directly on your site, or play in sandbox mode. No credit card required.

Get started today

World’s best intranet sites are designed using ShortPoint

Thousands of companies using ShortPoint everyday to design, brand and build award winning intranet sites.

Get started Learn more