Javascript: How to check if element is visible? - javascript

i'm using the lightweight zepto.js framework and now I need to test if an element on the page is visible or not … this my case:
A button triggers the function show_guides().
function show_guides() {
$('#guides').toggle();
if ( $('#guides').is(':visible') ) { // does not work
//$.cookie('guides_visible', 'true');
console.log("visible");
} else {
console.log("invisible");
//$.cookie('guides_visible', null);
}
}
If the $('#guides') are visible I want to save a cookie and if they are not I want to get rid of it.
However zepto.js doesn't support selectors like :visible so I have to find a different way.
Any ideas how to do that? Right now I'm getting the following error:
Uncaught Error: SYNTAX_ERR: DOM Exception 12
In the zepto documentation i've read this …
For basic support of jQuery’s non-standard pseudo-selectors such as
:visible, include the optional “selector” module.
But I have no idea how to include this.
Anybody out the who could help me out here? Thank you in advance.

You can check the display CSS property:
function show_guides() {
$('#guides').toggle();
if ( $('#guides').css('display') == 'block' ) {
console.log("visible");
} else {
console.log("invisible");
}
}

try
style.display="block";
and
style.display="hidden";

You can check visibility:visible/hidden, or display:block/none
$('#guides').css('visibility') == 'visible'
$('#guides').css('display') == 'block'

If all you want is to check visibility you can just use this
function visible(elem){
elem = $(elem)
return !!(elem.width() || elem.height()) && elem.css("display") !== "none"
}
taken straight from the zepto selectors plugin. Otherwise you can just include the selectors module from https://github.com/madrobby/zepto/blob/master/src/selector.js as Felix Kling suggested

Related

Onclick not working. Cannot read property 'click' of null

I keep receiving the following error from the browser console when loading my script into my Magento store. All that it is listening for is an onclick event on a div yet I receive this error:
"Uncaught TypeError: Cannot read property 'click' of null."
The script works in JSfiddle so I'm really not quite sure why it isn't working. I've tried enclosing it within a $( document ).ready() as well but I receive the same error.
Code:
var step = 0;
var deviceType = "";
var modelType = "";
function showGen(){
$('.phoneTypes').css("display", "none");
if (deviceType == "Samsung"){
$('.sphoneGens').css("display", "block");
}
if (deviceType == "iPhone"){
$('.iphoneGens').css("display", "block");
}
if (deviceType == "iPad"){
$('.ipadGens').css("display", "block");
}
}
// Pick Device Type
$('.choicelabel').click(function(){
deviceType = $(this).children('input').val();
showGen();
});
//Pick Device Gen
$('.choiceType').click(function(){
modelType = $(this).children('input').val();
//$(".iphoneGens").css("display", "none");
console.log(deviceType);
console.log(modelType);
$(this).parents(".row").hide();
});
Any help debugging this issue will be greatly appreciated.
TL;DR:
jQuery( document ).ready(function( $ ) {
// Code using $ as usual goes here.
// And document is ready too
});
What's the issue?
Prototype.js was loaded after jQuery and was overwrite global $ symbol.
How can we deal with it?
You still have jQuery global to use. Just use it everywhere, where you want to use $.
// Pick Device Type
jQuery('.choicelabel').click(function(){
deviceType = jQuery(this).children('input').val();
showGen();
});
//Pick Device Gen
jQuery('.choiceType').click(function(){
modelType = jQuery(this).children('input').val();
//jQuery(".iphoneGens").css("display", "none");
console.log(deviceType);
console.log(modelType);
jQuery(this).parents(".row").hide();
});
You can also to define some shorthand for simplify it:
jQ = jQuery;
Common best practice for cases like this is to use IIFE wrap for your code:
;(function($){ // see note-1
// Use $ here! It's jQuery now
$(function(){
// be sure DOM was loaded before work with it(ex: binding events)
});
})(jQuery);
This adds nothing to global scope and achieves what we need.
You always can inject some other libraries(prototypejs?) with alias what you want to this IIFE.
note-1: Semicolon before IIFE protects javascript from previous expression with missed semicolon to be interpreted as function call.
jQuery itself provides shorthand for this case:
jQuery( document ).ready(function( $ ) {
// Code using $ as usual goes here.
// And document is ready too
});
That site isn't using jQuery, it's using prototypejs

JScript Check if element exists and remove it

I'm trying to write a simple function in javascript to check if an element exists in the DOM and if it does remove, and if it doesn't, append it to the page, so far i've got this
if document.contains(document.getElementById("submitbutton") {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}
(lastDiv is just the div I want to append the div 'submitButton' to)
Yet i'm getting the error "Uncaught ReferenceError: myFunction is not defined"
Any help?
I'm aware this is a very newbie question, sorry about that
There is a syntax error in the code, if statements require parens
if (document.contains(document.getElementById("submitbutton"))) {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}
Check if element exists:
function removeID(_id ){
var e=document.getElementById(_id);
if(e!==null) e.remove();
}
removeID( "myElement" );

Class list in javascript not working

I don't know why, probably a simple answer, but I cant get this to work:
var classList = $(this).attr('class').split(/\s+/);
if (classList.contains('closebutton') == true) {
myActions();
}
Firebug tells me: TypeError: $(...).attr(...) is undefined
Use the hasClass() method instead:
if($(this).hasClass('class')) {
myActions();
}

How to tell if tinyMCE has been initated?

I initiate the tinyMCE like this in multiple tabs of JQuery:Tab. But I find to init tinyMCE multiple times yields readonly text areas. Thus I wish to check if tinyMCE is already initated. Is there a method like isInitated() or something similarly convenient there?
tinyMCE.init({
mode : "textareas",
theme : "simple",
width : "500",
height : "300"
});
You can use tinymce.editors.length to see if there is already an editor instance initalized (tinymce.editors.length > 0).
I know this question is old, but...in case someone is still looking for the holy grail:
in tinymce 4, you can pass a callback to tinyMCE.init like so:
tinyMCE.init({
//your regular parameters here...
setup: function(editor) {
editor.on('init', function() {
//all your after init logics here.
});
}
});
You can add init_instance_callback to init() parameters. This callback will be invoked when the tinymce instance is already inited.
I am using tincyMCE 4.7.2
I tried the answer of #Thariama and it did not work for me, I guess because his answer is valid for the older versions of the tinyMCE.
here is what worked for me (again, according to the version you are working on, this could not be helpful for you)
if (tinymce.initialized === true)
To check if "tinyMCE" is set just use this:
if(typeof(tinyMCE) != "undefined") {}
Try this:
if (typeof(tinymce.activeEditor.contentDocument) !== "undefined") {
// initialized
}
I found other solution for this.
Let's say that You've got element
<textarea id="tinymce0"></textarea>
Now let's say that You initialize it:
let config = { selector : '#tinymce0'};
tinymce.init(config);
After that You can make this:
let tinmyMceInstance = tinymce.get('tinymce0');
if( tinmyMceInstance === null ){
// Your code if not initialized
}
Keep in mind:
this works only with id, seems like using classname for get() won't work
Works in:
{
releaseDate: "2019-05-09",
majorVersion: "5",
minorVersion: "0.5",
}
So it's probably: 5.5

What version of IE uses window[objectName] instead of window.document[objectName]?

I am trying to use a Javascript callback to a Flex application embedded in my page. Looking through some examples, I've seen this code used to get a reference to the Flex application:
// Get the reference:
function thisFlexApp(appName) {
if(navigator.appName.indexOf ('Microsoft') != -1) {
return window[appName];
}
else {
return window.document[appName];
}
}
// Use it:
var someVariable = thisFlexApp('NameOfFlexApp').callbackMethod();
I used that method, but using IE9 I got errors indicating the "thisFlexApp" call didn't work. Turns out that window.document[appName] worked in IE9, but window[appName] didn't. Since I don't expect my government clients to be using IE9 yet, I'm wondering what version of IE this method would actually work on? Is there another test that would be better to use instead of the one above which just assumes all versions of IE work a certain way? Thanks in advance.
Don't check the browser version, check the browser's capabilities. You can just check if window[appName] exists, and if it does, use it.
function thisFlexApp(appName) {
if(window[appName]) {
return window[appName];
}
else {
return window.document[appName];
}
}
Or even shorter:
function thisFlexApp(appName) {
return window[appName] || window.document[appName];
}

Categories