Best JavaScript code snippet using testcafe
list_slider.js
Source:list_slider.js  
...39		 * Returns width of the viewport40		 *41		 * @return {Integer}42		 */43		function getViewportDimension() {44			return settings.is_horizontal ? $viewport.width() : $viewport.height();45		}46		function getListPosition() {47			return settings.is_horizontal ? $list.position().left : $list.position().top;48		}49		function getItemDimension($item) {50			return settings.is_horizontal ? $item.outerWidth(true) : $item.outerHeight(true);51		}52		function getItemPosition($item) {53			return settings.is_horizontal ? $item.position().left : $item.position().top;54		}55		/**56		 * Hides or shows buttons depends on the position of the list57		 * and size of the viewport58		 */59		function updateButtonsVisibility() {60			var viewport_dimension = getViewportDimension(),61				content_dimension = getContentDimension(),62				list_pos = getListPosition();63			//Don't display left button when list is scrolled to the left side or when there is nothing to scroll64			var hide_left_button = list_pos === 0 || content_dimension <= viewport_dimension,65				//Don't display right button when list is scrolled to the right side or when there is nothing to scroll66				hide_right_button = list_pos === viewport_dimension - content_dimension || content_dimension <= viewport_dimension;67			button_left.toggle(!hide_left_button);68			button_right.toggle(!hide_right_button);69		}70		function updateListPosition(position) {71			if (settings.is_horizontal) {72				$list.css('left', position);73			} else {74				$list.css('top', position);75			}76			if (!settings.is_animated) {77				updateButtonsVisibility();78			}79		}80		/**81		 * Centers icons relatively to the viewport82		 */83		function alignIcons() {84			var position = 0,85				viewport_dimension = getViewportDimension(),86				content_dimension = getContentDimension();87			//If icons don't fill entire viewport88			if (viewport_dimension > content_dimension) {89				//center them90				position = (viewport_dimension - content_dimension) / 2;91			}92			updateListPosition(position);93		}94		/**95		 * Determinates whether the item is visible in the viewport or not96		 *97		 * @return {Boolean}98		 */99		function isItemVisibleInViewport($item) {100			var list_pos = getListPosition(),101				viewport_dimension = getViewportDimension(),102				pos = settings.is_horizontal ? $item.position().left : $item.position().top,103				width = getItemDimension($item),104				pos_modified = pos + list_pos;//Its done to operate only in range <0, viewport_width>105			return (pos_modified >= 0 || pos_modified + width > 0) && pos_modified < viewport_dimension;106		}107		/**108		 * Returns position of the first or last visible item in the viewport109		 *110		 * @param {String} which111		 *     Possible values:112		 *     - 'first'113		 *     - 'last'114		 */115		function getVisibleItemInViewport(which) {116			var $item, items = $list.children(), i, l = items.length;117			for (i = 0; i < l; i++) {118				if (isItemVisibleInViewport($(items[i]))) {119					$item = $(items[i]);120					if (which === 'first') {121						return $item;122					}123				}124			}125			return $item;126		}127		function toggleScrolling(value) {128			if (settings.is_animated) {129				scroll_enabled = value;130			}131		}132		function scrollTo(list_position) {133			var position = Math.min(0, list_position);134			updateListPosition(position);135		}136		function scrollToBeginning() {137			var $first_visible = getVisibleItemInViewport('first'),138				$previous_item = $first_visible.prev();139			if ($previous_item.length) {140				scrollTo(getListPosition() + getItemDimension($previous_item));141			} else {142				toggleScrolling(true);143			}144		}145		function scrollToEnd() {146			var $last_visible = getVisibleItemInViewport('last'),147				$next_item = $last_visible.next();148			if ($next_item.length) {149				scrollTo(getListPosition() - getItemDimension($next_item));150			} else {151				toggleScrolling(true);152			}153		}154		function bindEvents() {155			//Initialize left button156			button_left = $el.find('.js-button-left').button({157				template : 'empty'158			}).on('btn:click', function() {159				toggleScrolling(false);160				scrollToBeginning();161			});162			//Initialize right button163			button_right = $el.find('.js-button-right').button({164				template : 'empty'165			}).on('btn:click', function() {166				toggleScrolling(false);167				scrollToEnd();168			});169			if (settings.enable_wheel_scrolling) {170				$list.on('mousewheel', function (e, delta) {171					if (!scroll_enabled) {172						return;173					}174					toggleScrolling(false);175					if (delta < 0) {176						scrollToEnd();177					} else {178						scrollToBeginning();179					}180				});181			}182			if (settings.is_animated) {183				$list.on('webkitTransitionEnd oTransitionEnd MSTransitionEnd transitionend', function (e) {184					updateButtonsVisibility();185					toggleScrolling(true);186				});187			}188		}189		function updateContent() {190			setContentDimension();191			//Update visibility of these buttons192			updateButtonsVisibility();193			//Center icons if they don't fill entire viewport194			alignIcons();195		}196		function scrollItemIntoView() {197			var $item = settings.scroll_item_into_view,198				item_pos = 0;199			if (!$item || $item.length === 0) {200				return;201			}202			if (isItemVisibleInViewport($item)) {203				return;204			}205			item_pos = getItemPosition($item);206			if (item_pos < 0) {207				scrollTo(getListPosition() - item_pos);208			} else {209				scrollTo(getViewportDimension() - (item_pos + getItemDimension($item)));210			}211			updateButtonsVisibility();212		}213		this.toggleAnimated = function (value) {214			settings.is_animated = value;215		};216		this.updateContent = function() {217			updateContent();218		};219		/**220		 * Clears up stuff before component will be removed221		 */222		this.destroy = function() {223			button_left.destroy();...get-viewport-size.js
Source:get-viewport-size.js  
...60      ...VIEWPORT_SIZE_DEFAULT,61      ...defaultSize62    };63  }64  let width = getViewportDimension('Width');65  width = isNumber(wMin) ? Math.max(width, wMin) : width;66  width = isNumber(wMax) ? Math.min(width, wMax) : width;67  let height = getViewportDimension('Height');68  height = isNumber(hMin) ? Math.max(height, hMin) : height;69  height = isNumber(hMax) ? Math.min(height, hMax) : height;70  return { width, height };71}...snow.js
Source:snow.js  
...11	this.dy = r ^ 1.5;12	this.iteration = 0;13	this.fill = fill;14}15function getViewportDimension() {16	var e = window, a = 'inner';17	if (!( 'innerWidth' in window )) {18		a = 'client';19		e = document.documentElement || document.body;20	}21	return {w:e[a + 'Width'], h:e[a + 'Height']};22}23function getRandom(min, max) {24  	return Math.random() * (max - min) + min;25}26var snowflakes = [];27var amount = 200028var ctx , cw , ch;29function init(){30  	var canvas = document.getElementById("cvs");31	var dim = getViewportDimension();32	cw = dim.w;33	ch = dim.h;34	canvas.width = cw;35	canvas.height = ch;36	if(canvas.getContext){37	    	ctx = canvas.getContext("2d");38    		for (var i = 0; i < amount; i++){39			x = getRandom(0, cw);40			y = getRandom(-ch, 0);41			z = getRandom(0, 10);42			dx = getRandom(-2, 10);43			dy = getRandom(1, 5);44			r = getRandom(0, 5);45			fill = '#EEEEEE';...LogoRainbow.js
Source:LogoRainbow.js  
1import styles from './LogoRainbow.less';2import LogoRainbowText from './LogoRainbowText';3import LogoRainbowIcon from './LogoRainbowIcon';4import Logo from '../Logo/Logo';5import React from 'react';6import PropTypes from 'prop-types';7import classnames from 'classnames';8const viewportDimensions = type =>9  ({10    default: { height: 68.031, width: 170.079 },11    compact: { height: 68.031, width: 68.031 }12  }[type]);13const getViewPortDimension = (type, dimension) =>14  viewportDimensions(type)[dimension];15export default function LogoRainbow({16  locale,17  svgClassName,18  invert,19  compact,20  textClass,21  ...restProps22}) {23  if (locale === 'NZ') {24    return (25      <Logo26        {...{27          locale,28          svgClassName,29          invert,30          compact,31          textClass,32          ...restProps33        }}34      />35    );36  }37  const svgClasses = classnames(svgClassName, {38    [styles.root]: true,39    [styles.invert]: invert40  });41  const type = (compact && 'compact') || 'default';42  const height = getViewPortDimension(type, 'height');43  const width = getViewPortDimension(type, 'width');44  return (45    <div {...restProps}>46      <svg47        className={svgClasses}48        id="sk-logo-pos"49        xmlns="http://www.w3.org/2000/svg"50        height={`${height}`}51        viewBox={`0 0 ${width} ${height}`}52        width={`${width}px`}53        y="0px"54        x="0px"55      >56        {!compact ? (57          <LogoRainbowText58            textClass={(invert && styles.invertedLogoText) || textClass}59          />60        ) : null}61        <LogoRainbowIcon />62      </svg>63    </div>64  );65}66LogoRainbow.propTypes = {67  locale: PropTypes.oneOf(['AU', 'NZ']),68  svgClassName: PropTypes.string,69  invert: PropTypes.bool,70  compact: PropTypes.bool,71  className: PropTypes.string,72  textClass: PropTypes.string73};74LogoRainbow.defaultProps = {75  locale: 'AU',76  svgClassName: '',77  className: '',78  textClass: styles.logoText...fit_viewport.js
Source:fit_viewport.js  
...15;(function(){16'use strict'17window.addEventListener('DOMContentLoaded',function(){18let viewportHeight, viewportWidth19function getViewportDimension(){20  viewportHeight = window.innerHeight21  viewportWidth = window.innerWidth22}23getViewportDimension()24let styleObj = document.createElement('style')25styleObj.setAttribute('module','fit_viewport')26document.documentElement.insertBefore(styleObj,document.body)27let rule_index = NaN28function refreshViewportDimensionCSS(){29  if(!isNaN(rule_index)){30    styleObj.sheet.deleteRule(rule_index)31  }32  rule_index = styleObj.sheet.insertRule(`html.fit_viewport {top: 0; left: 0; margin: 0; padding: 0; box-sizing: border-box; max-height: ${viewportHeight}px; max-width: ${viewportWidth}px; overflow: auto; height: 100%;}`)33}34refreshViewportDimensionCSS()35function onresize(){36  if(!document.documentElement.classList.contains('lock_fit_viewport')){37    getViewportDimension()38    refreshViewportDimensionCSS()39  }40}41window.addEventListener('resize',onresize)42document.documentElement.classList.add('fit_viewport')43})...Logo.js
Source:Logo.js  
1import styles from './Logo.less';2import LogoText from './LogoText';3import LogoIcon from './LogoIcon';4import React from 'react';5import PropTypes from 'prop-types';6import classnames from 'classnames';7const viewportDimensions = type =>8  ({9    default: { height: 68.031, width: 170.079 },10    compact: { height: 68.031, width: 68.031 }11  }[type]);12const getViewPortDimension = (type, dimension) =>13  viewportDimensions(type)[dimension];14export default function Logo({15  locale,16  svgClassName,17  invert,18  compact,19  textClass,20  iconClass,21  ...restProps22}) {23  const svgClasses = classnames(svgClassName, {24    [styles.root]: true,25    [styles.invert]: invert26  });27  const type = (compact && 'compact') || 'default';28  const height = getViewPortDimension(type, 'height');29  const width = getViewPortDimension(type, 'width');30  return (31    <div {...restProps}>32      <svg33        className={svgClasses}34        id="sk-logo-pos"35        xmlns="http://www.w3.org/2000/svg"36        height={`${height}`}37        viewBox={`0 0 ${width} ${height}`}38        width={`${width}px`}39        y="0px"40        x="0px"41      >42        {!compact ? (43          <LogoText44            textClass={(invert && styles.invertedLogoText) || textClass}45          />46        ) : null}47        <LogoIcon48          iconClass={(invert && styles.invertedLogoIcon) || iconClass}49        />50      </svg>51    </div>52  );53}54Logo.propTypes = {55  locale: PropTypes.oneOf(['AU', 'NZ']),56  svgClassName: PropTypes.string,57  invert: PropTypes.bool,58  compact: PropTypes.bool,59  className: PropTypes.string,60  textClass: PropTypes.string,61  iconClass: PropTypes.string62};63Logo.defaultProps = {64  locale: 'AU',65  svgClassName: '',66  className: '',67  textClass: styles.logoText,68  iconClass: styles.logoIcon...ui.js
Source:ui.js  
1import {Dimensions} from 'react-native';2/**3 * UI helper functions for the bounds, margin, etc calculation4 */5/**6 * Returns the screen dimension.7 *8 * @returns {number}9 */10export function getViewPortDimension() {11  return Dimensions.get('window');12}13/**14 * Returns the screen height.15 *16 *  @returns {number}17 */18export function getViewPortHeight() {19  return getViewPortDimension().height;20}21/**22 * Returns the screen width.23 *24 * @returns {number}25 */26export function getViewPortWidth() {27  return getViewPortDimension().width;28}29/**30 * Returns the screen width ratio.31 *32 * @param {number} percentageWidth33 * @returns {number}34 */35export function getWidthRatio(percentageWidth = 100) {36  return getViewPortWidth() * (percentageWidth / 100);37}38/**39 * Returns the screen height ratio.40 *41 * @param {number} percentageHeight42 * @returns {number}43 */44export function getHeightRatio(percentageHeight = 100) {45  return getViewPortHeight() * (percentageHeight / 100);46}47/**48 * Returns the margin; Consistently use the same margin.49 *50 * @returns {number}51 */52export function getMargin() {53  return getWidthRatio(6.25) - 10;54}55/**56 * Returns the header height.57 *58 * @returns {number}59 */60export function getHeaderHeight() {61  return getViewPortWidth() * (1 - getViewPortWidth() / getViewPortHeight());...browser.isDOMInViewport.js
Source:browser.isDOMInViewport.js  
...5 * @returns {Boolean} Result6 */7const isDOMInViewport = (dom) => {8    const r = dom.getBoundingClientRect()9    const { w, h } = getViewportDimension()10    return r.top >= 0 && r.left >= 0 && r.right <= w && r.bottom <= h11}...Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getViewportDimension = ClientFunction(() => {3    return {4        width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),5        height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)6    };7});8test('My Test', async t => {9    const { width, height } = await getViewportDimension();10    console.log(width, height);11});Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getViewportDimension = ClientFunction(() => {3    return {4    };5});6test('Getting viewport dimension', async t => {7    const { innerWidth, innerHeight, outerWidth, outerHeight } = await getViewportDimension();8        .expect(innerWidth).eql(800)9        .expect(innerHeight).eql(600)10        .expect(outerWidth).eql(800)11        .expect(outerHeight).eql(600);12});131 passed (2s)Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getViewportDimension = ClientFunction(() => {3    return {4    };5});6test('My Test', async t => {7    const { width, height } = await getViewportDimension();8    await t.expect(width).eql(1024);9    await t.expect(height).eql(768);10});Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getViewportDimensions = ClientFunction(() => {3    return {4    };5});6test('Get viewport dimensions', async t => {7    const { width, height } = await getViewportDimensions();8    console.log(width, height);9});Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getViewportDimension = ClientFunction(() => {3    return {4    };5});6test('My Test', async t => {7    const { width, height } = await getViewportDimension();8    console.log(width, height);9});10import { ClientFunction } from 'testcafe';11const getViewportSize = ClientFunction(() => {12    return {13    };14});15test('My Test', async t => {16    const { width, height } = await getViewportSize();17    console.log(width, height);18});19import { ClientFunction } from 'testcafe';20const getViewportSize = ClientFunction(() => {21    return {22    };23});24test('My Test', async t => {25    const { width, height } = await getViewportSize();26    console.log(width, height);27});28import { ClientFunction } from 'testcafe';29const getViewportSize = ClientFunction(() => {30    return {31    };32});33test('My Test', async t => {34    const { width, height } = await getViewportSize();35    console.log(width, height);36});37import { ClientFunction } from 'testcafe';38const getViewportSize = ClientFunction(() => {39    return {40    };41});42test('My Test', async t => {43    const { width, height } = await getViewportSize();Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My test', async t => {3    const getViewportSize = ClientFunction(() => {4        return {5            width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),6            height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)7        };8    });9    const viewportSize = await getViewportSize();10    console.log(viewportSize.width);11    console.log(viewportSize.height);12});13import { ClientFunction } from 'testcafe';14test('My test', async t => {15    const getViewportSize = ClientFunction(() => {16        return {17            width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),18            height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)19        };20    });21    const viewportSize = await getViewportSize();22    console.log(viewportSize.width);23    console.log(viewportSize.height);24});25import { ClientFunction } from 'testcafe';26test('My test', async t => {27    const getViewportSize = ClientFunction(() => {28        return {29            width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),30            height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)31        };32    });33    const viewportSize = await getViewportSize();34    console.log(viewportSize.width);35    console.log(viewportSize.height);36});37import { ClientFunction } from 'testcafe';38test('My test', async t => {39    const getViewportSize = ClientFunction(() => {40        return {41            width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),42            height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)43        };44    });Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My Test', async t => {3    const getViewportDimension = ClientFunction(() => {4        return {5        };6    });7    console.log(await getViewportDimension());8});9{ innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768 }10import { ClientFunction } from 'testcafe';11test('My Test', async t => {12    const getViewportDimension = ClientFunction(() => {13        return {14        };15    });16    console.log(await getViewportDimension());17});18{ innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768 }19import { ClientFunction } from 'testcafe';20test('My Test', async t => {21    const getViewportDimension = ClientFunction(() => {22        return {23        };24    });25    console.log(await getViewportDimension());26});27{ innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768 }28import { ClientFunction } from 'testcafe';29test('My Test', async t => {30    const getViewportDimension = ClientFunction(() => {31        return {Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('Getting viewport dimensions', async t => {3    const getViewportDimensions = ClientFunction(() => {4        return {5        };6    });7    const dimensions = await getViewportDimensions();8    console.log(dimensions.width, dimensions.height);9});10import { ClientFunction } from 'testcafe';11test('Getting window dimensions', async t => {12    const getWindowDimensions = ClientFunction(() => {13        return {14        };15    });16    const dimensions = await getWindowDimensions();17    console.log(dimensions.width, dimensions.height);18});19import { ClientFunction } from 'testcafe';20test('Getting window width', async t => {21    const getWindowWidth = ClientFunction(() => {22        return document.documentElement.clientWidth;23    });24    const width = await getWindowWidth();25    console.log(width);26});27import { ClientFunction } from 'testcafe';28test('Getting window height', async t => {29    const getWindowHeight = ClientFunction(() => {30        return document.documentElement.clientHeight;31    });32    const height = await getWindowHeight();33    console.log(height);34});35import { ClientFunction } from 'testcafe';36test('Getting window scroll', async t => {37    const getWindowScroll = ClientFunction(() => {Using AI Code Generation
1import {Selector} from 'testcafe';2test('My first test', async t => {3    const dimensions = await t.getViewportDimensions();4    console.log(dimensions.width, dimensions.height);5});6import {Selector} from 'testcafe';7test('My first test', async t => {8    const consoleMessages = await t.getBrowserConsoleMessages();9    console.log(consoleMessages);10});11import {Selector} from 'testcafe';12test('My first test', async t => {13    const consoleMessages = await t.getBrowserConsoleMessages();14    console.log(consoleMessages);15});16import {Selector} from 'testcafe';17test('My first test', async t => {18    const consoleMessages = await t.getBrowserConsoleMessages();19    console.log(consoleMessages);20});21import {Selector} from 'testcafe';22test('My first test', async t => {23    const consoleMessages = await t.getBrowserConsoleMessages();24    console.log(consoleMessages);25});26import {Selector} from 'testcafe';27test('My first test', async t => {28    const consoleMessages = await t.getBrowserConsoleMessages();29    console.log(consoleMessages);30});31import {Selector} fromUsing AI Code Generation
1import {Selector} from 'testcafe';2import { getViewportDimensions } from 'testcafe-browser-tools';3test('Test', async t => {4    const {width, height} = await getViewportDimensions('chrome');5    console.log(width);6    console.log(height);7});8const browserstack = require('testcafe-browser-provider-browserstack');9const { getViewportDimensions } = browserstack;10test('Test', async t => {11    const {width, height} = await getViewportDimensions('chrome');12    console.log(width);13    console.log(height);14});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
