AngularJs Virtual Repeater with a Grid

So I had a grid of images I displayed with an Angular ng-repeat, where the number of images was in the hundreds. This was just killing performance and overloading the DOM. I was getting super frustrated with the choppy scrolling and overall slow loading.

It occurred to me to use a virtual repeater, however, they either support vertical or horizontally stacked elements, not a grid. In order to get this to work, I need to structure my elements in a 2D array. That way I could still use the repeater on spitting out rows of image arrays and gain a performance boost through that.

2D Structure:
[
[img, img, img, img] ,
[img, img, img, img] ,
[img, img, img, img] ,
[img, img, img, img]
]

img = the image source url

The first thing I did, was make sure I knew the width of the total space for the grid and width of each element. I want to make sure I fill the space, so I did the math to know how many elements will fill the total space and that will be my column count. I recommend to setup some listeners on the grid width to catch changes from the user changing the window size, I won’t be showing that part in this example. The snippet below shows the creation of my 2D array that will be fed to the repeater.

//Passing in my array of images that I need to break down into a 2D array
//Also, including the width of the entire grid space and each image's uniformed width
function computeRows(imageArray, width, imageWidth) {
    var rows = [];
    if (imageArray) {
        const rowCount = width/ imageWidth;
        const copy = imageArray.slice(); //using a copy instead of affecting actual element
        while (copy.length) { //create the 2D array by looping through the imageArray and splicing it into chunks
            rows.push(copy.splice(0, rowCount)); 
        }
    }
    return rows;
}
//Will need to bind computeRows() to the scope

Once I have my 2D array, I bound it to me scope and used it in my template. I chose to use vs-repeat because it was very quick and easy to implement.

<div vs-repeat vs-excess="10">
    <div ng-repeat="row in rows">
        <img 
            ng-repeat="img in row"
            ng-src="{{img}}"/>
    </div>
</div>

That was it, the end result was awesome, vs-repeat handled just showing what was necessary for the user experience and loading the remainder DOM elements as the user scrolled through the grid.

AngularJS Setup Environment

Similar to yesterday’s post, I started a basic AngularJS startup environment, something I can just grab and program with whenever I want to start a new angular app. It’s just a pain re-setting up the environment each time.

Borrow if you like or contribute, thanks!


Screenshot of github.com
angular-setup-environment
Initial Angular Environment Setup

React Setup Environment

I started a react startup environment, something I can just grab and program with whenever I want to start a new React app. It’s just a pain re-setting up the environment each time.

Borrow if you like or contribute, thanks!


Screenshot of github.com
react-setup-environment
Initial React Environment Setup

Reference: https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel

Reordering an Array Based on Another Array’s Order in Javascript

So I had a problem, awhile ago, where I needed to reorder elements in an array based off of the order of another array. So I basically had to capture the order from one and apply it to another. In my case, both arrays had a common id field. However, with the model I have here, I was able to order additional arrays without the id field, if I needed to, which I did 🙂

Below is my code solution.

function getNewOrder() {
    //Get an identifier from the array you want to base the order on
    const newIds = newArrayOrder.map(x => x.id);
    
    //Get an identifier from the array you want to update
    const ids = arrayToOrder.map(x => x.id);
    
    //placeholder for order
    const order = [];
    
    //loop through the ids, pushing the arrayToOrder's index of the new order ids
    //We end up with an array of indexes
    for(let i = 0; i < ids.length; i++) {
      order.push(ids.indexOf(newIds[i]));
    }
    
    //reorder the array
    reorderIds(order, arrayToOrder);
}

//Preform the reordering
function reorderIds(order, arrayToOrder){
    //Get a copy of the array we want to change
    const temp = arrayToOrder.slice(0);
    
    //loop through the indexes
    //use the indexes to place the items in the right place from the copy into the original
    for(let i = 0; i < arrayToOrder.length; i++) {
      arrayToOrder[order[i]] = temp[i];
    }
}

 

Javascript Cloning and Moving DOM Elements to Mouse Position

So I was working with dragula, a super easy to use drag and drop library. However, I ran into an issue where when a user clicks the dragging element, I wanted everything in the background to collapse. This messed up the dragging element’s position in relation to where the mouse’s location. In most cases when you drag and drop an element, it hovers wherever your mouse is located. In my case, when I shifted everything, the element I wanted to drag was no longer located where I clicked but rather it moved and hovered in the wrong spot with the wrong offset from my mouse. In using this library, I didn’t have access to changing their inner coding offset logic, so I needed to come up with my own fix. In the end, I decided to hide their floating mouse DOM element and create my own, that I had control over. The following code shows how to do just that!

Happy coding! Let me know if you have any comments or improvements.

//call this function when we want to initiate the listener for moving the mouse
//For instance, call this function once the user starts dragging an element
//requires an event and element to be passed.
function startMouseMove(e, element) {
    $('.my-background-content').css( 'display', 'none' ); //collapse background elements
    const container = $(element).find('.item-to-clone').clone().appendTo('.my-container'); //clone the element you want to hover around mouse
    $(container).attr('id', 'cursor_element'); //give the clone element an id so we can reference it later
    $('#cursor_element').css({'position': 'fixed', 'top': e.pageY, 'left': e.pageX}); //set clone element's position to mouse's position
    $document.on('mousemove', moveElement); //bind mouse event
}
 
function moveElement(e) {
    const y = e.pageY; //get y position
    const x = e.pageX; //get x position
    $('#cursor_element').css({'top': y, 'left': x}); //move the position of the element to match mouse, whenever mouse moves
}
 
//call this function when we want to stop the listener for moving the mouse
//For instance, call this function once the user drops a dragging element
function stopMouseMove() {
    $('#cursor_element').remove(); //delete cloned element
    $('.my-background-content').css( 'display', '' ); //un-collapse background elements
    $document.unbind('mousemove', moveElement); //unbind mouse event
}

Note that $document and JQuery must be declared/injected into the controller for this to work.

The above code requires JQuery, but you could easily use vanilla Javascript. Check this out for event help and this out for DOM selection.

Javascript Mousemove Scroll Event

Sometimes you just want the window to scroll when the user moves their cursor to the top or bottom of the page. For instance, some drag and drop events block out scrolling and it is difficult for users to drag their element where they need it to go without it. Wouldn’t it be nice if we could use something to detect where the mouse is and scroll for the user automatically? Well we can! The following code insert does just that! For it, I am using angularJs events and JQuery element selection but you can use vanilla javascript to do both of these. Check this out for vanilla javascript event help and this out for DOM selection.

//call this function when we want to initiate the listener for moving the mouse
//For instance, call this function once the user starts dragging an element
function startMouseMove() {
    $document.on('mousemove', scrollWindow);
}

function scrollWindow(e) {
    const y = e.pageY; //This collects details on where your mouse is located vertically
    const container = $('.my-container'); //Replace this with the element class(.) or id(#) that needs to scroll
    const buffer = 200; //You can set this directly to a number or dynamically find some type of buffer for the top and bottom of your page
    const containerBottom = container.offset().top + container.outerHeight(); //Find the bottom of the container
    const containerTop = container.offset().top; //Find the top position of the container
    const scrollPosition = container.scrollTop(); //Find the current scroll position
    const scrollRate = 20; //increase or decrease this to speed up or slow down scrolling

    if (containerBottom - y < buffer) { //If the bottom of the container's position minus y is less than the buffer, scroll down!
      container.scrollTop(scrollPosition + scrollRate);
    } else if (containerTop + y < buffer) { //If the top of the container's position plus y is less than the buffer, scroll up!
      container.scrollTop(scrollPosition - scrollRate);
    }
}

//call this function when we want to stop the listener for moving the mouse
//For instance, call this function once the user drops a dragging element
function stopMouseMove() {
    $document.unbind('mousemove', scrollWindow);
}

Note that $document and JQuery must be declared/injected into the controller for this to work.

Happy coding!

Creating a Sharepoint ‘Like’ through SOAP Requests

Sharepoint is not my most favorite environment to program in but I figure I’d share a cool javascript app I put together that communicates with Sharepoint’s SOAP API to add on to custom ‘like’ buttons (just like facebook!) With this feature, users can ‘like’ sharepoint items without going through the crazy sharepoint interface. This javascript can be added to a web interface, and users can ‘like’ items from there!

None of this garbage
None of this garbage

I wrote some javascript/jquery code that can easily retrieve the number of ‘likes’ for a sharepoint list item or list. The script basically queries Sharepoint’s built in social services for the tag count with SOAP POST calls.

Get Like Count

Here is the script to get ‘like’ count:


<script>

function GetLikeCountFromService(strURL) {

var count = 0;

//change the webMethod var to match up to the correct sharepoint _vti_bin location. (https://msdn.microsoft.com/en-us/library/office/Bb862916(v=office.12).aspx)

var webMethod = \'/_vti_bin/SocialDataService.asmx?op=GetTagTermsOnUrl\';

var soapEnv = "<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'> <soap:Body><GetTagTermsOnUrl xmlns=\'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService\'> <url>" + strURL + "</url> <maximumItemsToReturn>1</maximumItemsToReturn> </GetTagTermsOnUrl> </soap:Body> </soap:Envelope>";



$.ajax({

type: "POST",

async: true,

url: webMethod,

data: soapEnv,

contentType: "text/xml; charset=utf-8",

dataType: "xml",

success: function(data, textStatus, XMLHttpRequest) {

count  = $(\'SocialTermDetail\', data).find(\'Count\').text();

}

});

return count;

}

</script>

Called by: GetLikeCountFromService(‘<LIST OR LIST ITEM URL>’)

Example: GetLikeCountFromService(‘http://mysharepoint/list/item’)

Here is the script to post ‘likes’ to an article. Once again it’s a nice javascript that can put into an HTML header or what not.

Emulate a ‘like’

Script to post a ‘like’:


function AddLikeCountFromService(strURL) {

//change the webMethod var to match up to the correct sharepoint _vti_bin location. (https://msdn.microsoft.com/en-us/library/office/Bb862916(v=office.12).aspx)

var webMethod = \'/_vti_bin/SocialDataService.asmx?op=GetAllTagTermsForUrlFolder\';

var soapEnv = "<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'><soap:Body><GetAllTagTermsForUrlFolder xmlns=\'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService\'><urlFolder>"+strURL+"</urlFolder><maximumItemsToReturn>1</maximumItemsToReturn></GetAllTagTermsForUrlFolder></soap:Body></soap:Envelope>";

$.ajax({

type: "POST",

async: true,

url: webMethod,

data: soapEnv,

contentType: "text/xml; charset=utf-8",

dataType: "xml",

success: function(data, textStatus, XMLHttpRequest) {

var info  = ($(\'SocialTermDetail\', data).text()).split(" ");

var guid = (info[0]).substring(0, info[0].length - 1);

//change the webMethod var to match up to the correct sharepoint _vti_bin location. (https://msdn.microsoft.com/en-us/library/office/Bb862916(v=office.12).aspx)

webMethod = \'/_vti_bin/SocialDataService.asmx?op=AddTag\';

//In the soapEnv request, you can change the title field to anything. This is the title of the thing the user is liking.

soapEnv = "<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'> <soap:Body><AddTag xmlns=\'http://microsoft.com/webservices/SharePointPortalServer/SocialDataService\'><url>"+strURL+"</url><termID>"+guid+"</termID><title>I like it!</title><isPrivate>false</isPrivate></AddTag></soap:Body> </soap:Envelope>";

$.ajax({

type: "POST",

async: true,

url: webMethod,

data: soapEnv,

contentType: "text/xml; charset=utf-8",

dataType: "xml",

success: function(data, textStatus, XMLHttpRequest) {

}

});

}

});

Called By:

Example: AddLikeCountFromService(‘<LIST OR LIST ITEM URL>’)

AddLikeCountFromService(‘http://mysharepoint/list/item’)