How to use verifyViewport method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

admin.js

Source: admin.js Github

copy
1$(document).ready(function() {
2    $('table.display').DataTable();
3} );
4$('[data-toggle="tooltip"]').tooltip();
5
6const verifyViewport = ()=>{
7    let viewport = $(window).width();
8
9    if ( viewport <= 1200 ) {
10        $("#myTable2").addClass("table-responsive");
11    }
12    else {
13        $("#myTable2").removeClass("table-responsive");
14    }
15}
16$(window).ready(function() {
17    verifyViewport();
18});
19$(window).resize(function(){
20    verifyViewport();
21});
22
Full Screen

_portfolio.js

Source: _portfolio.js Github

copy
1/*
2|--------------------------------------------------------------------------
3| Controller Portfolio
4|--------------------------------------------------------------------------
5*/
6var projectsJson = {};
7APP.controller.Portfolio = {
8 
9	init : function () {
10
11		this.setup();
12		this.portfolio();
13 
14    },
15
16	setup : function() {
17
18
19
20	},
21 
22	portfolio : function () {
23
24		APP.controller.Portfolio.getProjects();
25
26	},
27
28	//Get Projects
29	getProjects : function () {
30					
31		$.ajax({
32				type: "GET",
33				dataType: 'json',
34				url: "./assets/json/portfolio.json",
35				beforeSend: function () {
36						//APP.component.Loading.show();
37				},
38				success: function (result) {
39					APP.controller.Portfolio.setProjects(result.projects);
40					projectsJson = result;
41				},
42				error: function (result) {
43					APP.component.Alert.customAlert('Alerta!', 'Erro desconhecido. Entre em contato com a Central de Atendimento.');
44				},
45				complete: function (result) {
46						//APP.component.Loading.hide();
47				}
48		}).promise().done(function () {
49			//Portfolio
50			APP.component.MixItUp.init('.gallery');
51			APP.controller.Portfolio.clickFilter();
52			APP.controller.Portfolio.setFilter();
53			//APP.controller.Portfolio.verifyViewport();
54			//Gallery
55			APP.controller.Gallery.init();
56		});
57
58	},
59
60	setProjects : function (result) {
61		var html = '';
62		
63		if (result.length > 0) {
64				$(result).each(function (i) {
65					html += `
66					<div class="mix ${APP.controller.Portfolio.setListFilters(this.filters)}" data-order="${i+1}">
67							<div class="card">
68									<div class="cover" style="background-image: url(./assets/img/portfolio/${(this.company != '' ? slugify(this.company, "") + '-' : '') + slugify(this.name, "")}/${this.cover});">
69									</div>
70									<div class="description">
71											<h2 class="name">${this.name}</h2>
72											<span class="company">${this.company}</span>
73									</div>
74									<img src="./assets/img/shared/ratio16x9.png" alt="" class="ratio">
75							</div>
76					</div>
77					`
78				});
79		}
80
81		$('.gallery').append(html)
82		
83	},
84
85	setListFilters : function (items) {
86		var filters = '';
87		if (items.length > 0) {
88			$(items).each(function (i) {
89				filters += `
90					${this}
91				`
92			});
93		}
94
95		return filters;
96
97	},
98
99	setTechnologies : function (technologies) {
100		var technologies = `
101				${Array(technologies.length).join(0).split(0).map((item, e) => `
102						<span>${this.areaEspecializacao[e]}</span>
103				`).join('')}
104		`
105		return technologies;
106
107	},
108
109	mixItUpClear : function () {
110
111			(function() { $('#gallery').removeClass('waypoint') }, 2000);
112
113	},
114	
115	//Filter
116	setFilter : function () {
117
118			APP.controller.Portfolio.posFilterBar($('.filter').first());
119
120	},
121
122	clickFilter : function () {
123			$('.filter').click(function(){
124				//APP.controller.Portfolio.verifySlickPortfolio();
125				APP.controller.Portfolio.posFilterBar(this);
126			});
127	},
128
129	posFilterBar : function (elem) {
130		var origin = $(elem).parent().offset().left;
131		var pos = $(elem).offset().left;
132
133		$('.float-bar').css({
134				left: pos - origin,
135				width: $(elem).innerWidth()
136		});
137		$('.float-bar .list-bar').css('left', (pos - origin) * -1);
138	},
139
140	verifySlickPortfolio : function () {
141
142		if ($(window).width() < 480) {
143			if ($('.slick-initialized').length > 0) {
144				APP.controller.Portfolio.removeSlickPortfolio();
145				APP.controller.Portfolio.setSlickPortfolio();
146			}
147		}
148
149	},
150
151	//Set Slick Mobile
152	verifyViewport : function () {
153		
154		if ($(window).width() < 480) {
155			APP.controller.Portfolio.setSlickPortfolio();
156		} else if ($('.slick-initialized').length > 0) {
157			APP.controller.Portfolio.removeSlickPortfolio();
158		}
159
160	},
161
162	setSlickPortfolio : function () {
163
164		$('.gallery').slick({
165
166			dots: true,
167			arrows: false,
168			infinite: true,
169			speed: 300,
170			slidesToShow: 1,
171			slidesToScroll: 1,
172			lazyLoad: 'ondemand',
173			centerMode: true,
174        	centerPadding: '40px'
175  
176		});
177
178
179	},
180
181	removeSlickPortfolio : function () {
182		$('.gallery').slick('unslick');
183	},
184
185}
186
Full Screen

profile.js

Source: profile.js Github

copy
1(function($) {
2    // SETUP AJAX
3    $.ajaxSetup({
4        headers:
5            {'X-CSRF-TOKEN': $('meta[name="_csrf"]').attr('content')}
6    });
7
8    // FOLLOW BTN SUBMIT A FOLLOW REQUEST AJAX
9    $( "#addFriend" ).click(function() {
10        let formData = {"friendId" : userId}
11        let url = "/users/follow";
12        $.ajax({
13            type: "POST",
14            contentType: "application/json",
15            url: url,
16            data: JSON.stringify(formData),
17            dataType: 'json'
18        });
19        setTimeout(function () {
20            $('#addFriend').text()== "Follow" ? $('#addFriend').text('Unfollow'): $('#addFriend').text('Follow');
21        },1000)
22    });
23
24    const getMoreSuggestions = ()=>{
25        $.ajax({'url': '/users/'+userId+'/matches'}).done(function (recipes) {
26            $('#suggestionsTab').html(recipes);
27            $('[data-toggle="tooltip"]').tooltip();
28        });
29    }
30
31    // SUGGESTIONS AJAX
32    $( "#suggestions" ).click(function() {
33          getMoreSuggestions();
34        $.post( '/users/'+userId+'/matches/update', function( data ) {
35            userMatchCount = data;
36        });
37        $("#notification").html("");
38    });
39
40    // PANTRY AJAX
41    let pantryInventory;
42    let inventoryIngredients;
43    const makePantryAjaxCall = ()=>{
44        pantryInventory = [];
45        inventoryIngredients = [];
46        $.ajax({'url': '/api/users/'+userId+"/pantry"}).done(function (response) {
47            response.pantryIngredients.forEach(function(item) {
48                inventoryIngredients.push(item);
49                pantryInventory.push(item.ingredient.name.toLowerCase());
50            });
51        });
52    };
53
54    // CREATE HTML FOR PANTRY TEMPLATE
55    const renderPantry = ()=>{
56        if( inventoryIngredients.length > 0 ){
57            $("#ingredientsTable").removeClass("d-none");
58        }else{
59            if(!$("#ingredientsTable").hasClass("d-none")){
60                $("#ingredientsTable").addClass("d-none")
61            }
62        }
63        // SORT INGREDIENTS BY NAME
64        inventoryIngredients.sort((a, b) => (a.ingredient.name > b.ingredient.name) ? 1 : -1);
65        let pantryHtml = "";
66        // ADD ROWS TO PANTRY TABLE
67        inventoryIngredients.forEach((item)=>{
68            pantryHtml += '<tr id="'+item.id+'">'+
69                '<td class="green-text" type="button" data-toggle="modal" data-target="#ingredientModal">' + item.ingredient.name + '</td>'+
70                '<td class="green-text"  data-amount-float="'+item.amount+'-'+item.unit+'"><span class="rational">' + item.amount + '</span><span> ' + item.unit+ '</span></td>'+
71                '<td class="qty">'+
72                '<span class="font-weight-bold red-text" type="button" data-toggle="modal" data-target="#deleteIngredientModal" style="font-size: 1.2em!important;">X</span>' +
73                // '<span  type="button" data-toggle="modal" data-target="#ingredientModal" ><i class="fas fa-pencil-alt"></i></span>'+
74                '</td>'+
75                '</tr>'
76            ;
77        })
78        // RENDER TEMPLATE
79        $('#ingredientsBody').html(pantryHtml);
80    }
81
82    // ONCLICK EVENT FOR USER PANTRY
83    $( "#userPantry" ).click(function() {
84        // GET PANTRY INGREDIENTS
85        makePantryAjaxCall();
86        // RENDER INGREDIENTS
87        setTimeout(function() {
88            renderPantry();
89            convertAllRationals();
90        }, 500);
91    });
92
93    // AUTO-SEARCH INGREDIENTS FOR PANTRY
94    $(document).on('keyup',"#ingredientSearch",function(){
95        let searchResults = $('#searchResults');
96        let searchInput = this.value.trim();
97        /* dont display any suggestions if empty string */
98        if(this.value === "") {
99            searchResults.empty();
100            /* if input string is already in pantry notify user */
101        }else if(pantryInventory.includes(searchInput.toLowerCase())){
102            searchResults.empty();
103            searchResults.append(
104                '<button id="ingredientInput" type="button" class="btn btn-yellow rounded-pill m-2" data-toggle="modal" data-target="#ingredientModal" disabled>'+searchInput.toLowerCase()+' is in pantry</button>'
105            );
106        }
107        /* create suggestions buttons that user can select */
108        else{
109            searchResults.empty();
110            searchResults.append(
111                '<button id="ingredientInput" type="button" class="btn btn-yellow rounded-pill m-2" data-toggle="modal" data-target="#ingredientModal">'+searchInput.toLowerCase()+'</button>'
112            );
113
114            /* search existing ingredients list to auto suggest ingredients and if not in list allow user to select own input */
115            ingredientsList.filter(function(ingredient){
116                if(ingredient.toLowerCase() === searchInput.toLowerCase()){
117                    $("#ingredientInput").addClass("d-none");
118                }
119                if (ingredient.toLowerCase().startsWith(searchInput.toLowerCase())) {
120                    searchResults.append(
121                        '<button type="button" class="btn btn-yellow rounded-pill m-2" data-toggle="modal" data-target="#ingredientModal">'+ingredient+'</button>'
122                    );
123                }
124            });
125            searchResults.append("</div>");
126        }
127    });
128
129    // USER PANTRY ADD NEW PANTRY INPUT CLICK
130    $(document).on('click',"#showIngredientForm", function () {
131        let input = $("#ingredientSearch");
132        if(input.hasClass("d-none")){
133            $(this).prop('value', 'close');
134            input.removeClass("d-none");
135        }
136        else{
137            $(this).prop('value', 'Add New Ingredient');
138            $("#searchResults").empty();
139            $("#ingredientSearch").val("")
140            input.addClass("d-none");
141        }
142    })
143
144    // INGREDIENT MODAL ON SHOW DYNAMIC INFO
145    $('#ingredientModal').on('show.bs.modal', function (event) {
146        let openModal = $(this);
147        let button = $(event.relatedTarget); // Button that triggered the modal
148        let tagType = button[0].tagName;
149        let clickedIngredient; // Ingredient name to be used
150        /* if tag type is span change ingredient form to an update form */
151        if(tagType === "TD"){
152            /* get data for update form from the tr element */
153            let pantryIngId = button.parent()[0].getAttribute("id");
154            let tableRow = button.parent()[0];
155            let amountUnit = tableRow.firstChild.nextSibling.getAttribute("data-amount-float").split("-");
156            let unit = amountUnit[1].split(" ")[0].toLowerCase();
157            clickedIngredient = tableRow.firstChild.innerText;
158            /* set form values for update */
159            openModal.find('select').val(unit); // set unit select value
160            openModal.find('.modal-title').text("Update " + clickedIngredient); // place ingredient name on title
161            openModal.find('.modal-body input').val(clickedIngredient);
162            count.val(parseFloat(amountUnit[0]));// set amount value
163            $("#typeSubmit").html(
164                '<input name="id" type="hidden" value="'+pantryIngId+'"/>'+
165                '<button id="updateIngredient" type="submit" class="btn btn-green">Update</button>'
166            );// set edit submit button
167        }
168        /* else ingredient form is a new ingredient form */
169        else{
170            clickedIngredient = button[0].innerHTML;
171            $("#typeSubmit").html('<button id="addIngredient" type="submit" class="btn btn-green">Save</button>');
172            openModal.find('.modal-title').text("Add "+ clickedIngredient +" to pantry");
173            openModal.find('.modal-body input').val(clickedIngredient);
174            count.val(1);
175        }
176
177    })
178
179    // Plus Minus Count for Ingredient Form modal
180    let count = $('#ingredientForm').find('input.count');
181    $(document).on('click','#formQty .plus',function(){
182        if (count.val() == 0) {
183            count.val(0);
184        }
185        count.val(parseFloat(count.val()) + 1);
186    });
187    $(document).on('click','#formQty .minus',function(){
188        count.val(parseFloat(count.val()) - 1);
189        if (count.val() == 0) {
190            count.val(1);
191        }
192    });
193
194    // ON INGREDIENT MODAL SUBMIT POST REQUEST ADD INGREDIENT TO PANTRY
195    $(document).on('click','#addIngredient',function(){
196        $('#ingredientModal').modal('toggle');
197        let form = $('#ingredientForm');
198        let url = "/pantry/ingredient/new";
199        let formData = JSON.stringify({
200            "name" : form.find('input#ingredientName').val(),
201            "amount": form.find('input.count').val(),
202            "unit" : form.find('select  option:selected').text()
203        });
204        // CREATE POST REQUEST FOR INGREDIENT
205        $.ajax({
206            type: "POST",
207            contentType: "application/json",
208            url: url,
209            data: formData,
210            dataType: "json",
211        });
212        // GET PANTRY INGREDIENTS AFTER CREATE
213        setTimeout(function() {
214            makePantryAjaxCall();
215        }, 1000);
216        // RENDER THE PANTRY INGREDIENTS
217        setTimeout(function() {
218            $("#searchResults").empty();
219            $("#ingredientSearch").val("")
220            renderPantry();
221            getMoreSuggestions();
222            convertAllRationals();
223        }, 1500);
224        // RENDER NOTIFICATION IF NEW SUGGESTIONS FROM NEW INGREDIENTS
225        setTimeout(function () {
226            updateNotification()
227        },2000);
228        return false;
229    })
230
231    // UPDATE INGREDIENT
232    $(document).on('click','#updateIngredient',function(){
233        $('#ingredientModal').modal('toggle');
234        let form = $('#ingredientForm');
235        let url = "/pantry/ingredient/edit";
236        let formData = JSON.stringify({
237            "id" : form.find('input[name=id]').val(),
238            "amount": form.find('input.count').val(),
239            "unit" : form.find('select  option:selected').text()
240        });
241        // MAKE UPDATE POST REQUEST FOR INGREDIENT
242        $.ajax({
243            type: "POST",
244            contentType: "application/json",
245            url: url,
246            data: formData,
247            dataType: "json",
248        });
249        // GET PANTRY INGREDIENTS AFTER UPDATE
250        setTimeout(function() {
251            makePantryAjaxCall();
252        }, 1000);
253        // RENDER THE PANTRY INGREDIENTS
254        setTimeout(function() {
255            renderPantry();
256            convertAllRationals();
257
258        }, 1500);
259        return false;
260    });
261
262    // INGREDIENT MODAL ON SHOW DYNAMIC INFO
263    $('#deleteIngredientModal').on('show.bs.modal', function (event) {
264        let openModal = $(this);
265        let button = $(event.relatedTarget); // Button that triggered the modal
266        let clickedIngredient; // Ingredient name to be used
267        /* get data for update form from the tr element */
268        let pantryIngId = button.parent().parent()[0].getAttribute("id");
269        let tableRow = button.parent().parent()[0];
270        clickedIngredient = tableRow.firstChild.innerText;
271        /* set form values for update */
272        openModal.find('.modal-title').text("Remove " + clickedIngredient); // place ingredient name on title
273        openModal.find('.modal-body input').val(pantryIngId);
274    })
275
276    // ON DELETE INGREDIENT MODAL SUBMIT REMOVE INGREDIENT FROM PANTRY
277    $("#deleteIngredient").submit(function(){
278        $('#deleteIngredientModal').modal('toggle');
279        let form = $(this);
280        let ingredientId = form.find('input[name=id]').val(); // GETS INGREDIENT ID
281        let url = '/api/pantry-ingredients/'+ingredientId+'/delete';
282        // MAKE DELETE REQUEST FOR INGREDIENT
283        $.ajax({
284            type: "POST",
285            url: url,
286            contentType: "application/json",
287            dataType: 'json'
288        });
289        // AFTER DELETE GET PANTRY INGREDIENTS
290        setTimeout(function () {
291            makePantryAjaxCall();
292        }, 1000);
293        // RENDER THE PANTRY INGREDIENTS
294        setTimeout(function () {
295            renderPantry();
296            convertAllRationals();
297        }, 1500);
298        return false;
299    })
300
301    $('[data-toggle="tooltip"]').tooltip();
302
303    const verifyViewport = ()=>{
304        let viewport = $(window).width();
305
306        if ( viewport <= 759 ) {
307            if($(".nav-tabs").children().length<5){
308                $(".nav-tabs").children().each(function () {
309                    $(this).removeClass("col-4")
310                    $(this).addClass("col-3");
311                })
312            }
313        }
314        else {
315            $(".nav-tabs").children().each(function () {
316                $(this).addClass("col-4")
317                $(this).removeClass("col-3");
318            })
319        };
320    }
321    $(window).ready(function() {
322        verifyViewport();
323    });
324    $(window).resize(function(){
325        verifyViewport();
326    });
327
328    $("#draftTab").click(function () {
329        if($("#draftRecipes").hasClass("d-none")){
330            $("#draftRecipes").removeClass("d-none");
331            $("#publishedRecipes").addClass("d-none");
332        }
333
334    });
335    $("#publishedTab").click(function () {
336        if($("#publishedRecipes").hasClass("d-none")){
337            $("#draftRecipes").addClass("d-none");
338            $("#publishedRecipes").removeClass("d-none");
339        }
340    });
341
342    $(".search-btn").click(function(){
343        $(".input-box").toggleClass("active").focus;
344        $(this).toggleClass("animate");
345        $(".input-box").val("");
346    });
347
348    // NOTIFICATION
349    let userMatchCount = parseInt($("#notification").data('internalid'));
350    const updateNotification = ()=>{
351        // the actual notification count
352        let notificationCount = parseInt($("#notification").text());
353
354        // the users current matching recipes
355        let currentMatches = $(".suggestions-card").length;
356
357        // if the user doesnt have notifcations update count
358        if(isNaN(notificationCount)){
359            notificationCount = currentMatches - userMatchCount;
360        }else{
361            let tempCount = currentMatches - userMatchCount;
362            if(tempCount > notificationCount){
363                notificationCount = tempCount;
364            }
365        }
366        if(notificationCount <= 0){
367            notificationCount = "";
368        }
369        // render the count to html notfication
370        $("#notification").html(notificationCount);
371    }
372})(jQuery);
373
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)