0

I want to apply the same script on multiple pages, but I need to store some var inside, which may not be present on particular pages.

window.onorientationchange = function () {
var $t1 = $(".test1")[0];
var $t2 = $(".test2")[0];
var $t3 = $(".test3")[0];
var $t4 = $(".test4")[0];
var $t5 = $(".test5")[0];
// do some stuff
}

I want to store this code in .js file and then apply it across several pages, the problem is that some of this var's are not present on particular pages, how do I make it universal?

Also

If I add lines like:

if (window.matchMedia("(orientation: portrait)").matches) {        
  if ($t1.is(":empty") && $t2.is(":visible")) {}}

inside mentioned event listener, how do I deal with an "empty" var's, which is not defined on the previous step?

  • 2
    There is too much information lacking in your question for readers to be able to accurately answer it. You must understand that we don't know how your project is organized or how it's intended to work. Add more information on what you're attempting to do. – kemicofa ghost Jan 15 '19 at 17:39
  • Cookie may be is one easy way to cross the pages – Tony Dong Jan 15 '19 at 17:42
  • If I am undestanding correctly you want to test if your jQuery selector found any matches. To see if the element exists, use .length on your jQuery selector https://stackoverflow.com/a/299821/5569485 – Eric Phillips Jan 15 '19 at 17:45
  • How I do this properly in my case? Do I apply it to var? If so then how do I deal with lines inside the function that contains empty var's? @EricPhillips –  Jan 15 '19 at 17:51

1 Answers1

-1

Several things.

Based on your variable naming, it looks like you are expecting $t1 to be a jQuery object.

However, when you try to access an element by index [0], you are returning the first element that matched the selector, no longer wrapped as a jQuery object.

What you want is to use the .eq(0) function to access the element by index, so a jQuery object is returned

https://api.jquery.com/eq/

var $t1 = $(".test1").eq(0);

At that point, you can use the .length test to check if your $t1 contains any elements

window.onorientationchange = function () {
    var $t1 = $(".test1").eq(0);
    // ...

    if($t1.length){
       // do stuff with $t1
    }
}
Eric Phillips
  • 866
  • 7
  • 23
  • 1
    Thank you for that clarification! (However, when you try to access an element by index [0]...) @Eric Phillips –  Jan 15 '19 at 18:18