I need to monitor the display state of an element. I'm using the following code
if WebKitMutationObserver?
observer = new WebKitMutationObserver observerFunc
observer.observe el, {attributes:true}
else
el.addEventListener "DOMAttrModified",(event)->
wrapper.style.display = el.style.display
return
However this does not work in Safari.
Also, typing "WebKitMutationObserver" in developer tools immediate window in Chrome gives the output
function WebKitMutationObserver() { [native code] }
while in Safari (v 5.1.7), this gives an error with the message
"Can't find variable: WebKitMutationObserver"
Could it be that Safari does not support WebkitMutationObserver? And if so, is there an alternative which I could use for this?
The newest Safari (6.0) does include WebKitMutationObserver. For older Safari's, here's some code we have used that fakes a DOMAttrModified event when you use setAttribute or removeAttribute to change an attribute. Note that this doesn't work if the browser itself changes an attribute internally.
var win = window;
var doc = win.document;
var attrModifiedWorks = false;
var listener = function () { attrModifiedWorks = true; };
doc.documentElement.addEventListener("DOMAttrModified", listener, false);
doc.documentElement.setAttribute("___TEST___", true);
doc.documentElement.removeAttribute("___TEST___", true);
doc.documentElement.removeEventListener("DOMAttrModified", listener, false);
if (!attrModifiedWorks)
{
This.DOMAttrModifiedUnsupported = true;
win.HTMLElement.prototype.__setAttribute = win.HTMLElement.prototype.setAttribute;
win.HTMLElement.prototype.setAttribute = function fixDOMAttrModifiedSetAttr (attrName, newVal)
{
var prevVal = this.getAttribute(attrName);
this.__setAttribute(attrName, newVal);
newVal = this.getAttribute(attrName);
if (newVal != prevVal)
{
var evt = doc.createEvent("MutationEvent");
evt.initMutationEvent
( "DOMAttrModified"
, true
, false
, this
, prevVal || ""
, newVal || ""
, attrName
, (prevVal == null) ? win.MutationEvent.ADDITION : win.MutationEvent.MODIFICATION
);
this.dispatchEvent(evt);
}
}
win.HTMLElement.prototype.__removeAttribute = win.HTMLElement.prototype.removeAttribute;
win.HTMLElement.prototype.removeAttribute = function fixDOMAttrModifiedRemoveAttr (attrName)
{
var prevVal = this.getAttribute(attrName);
this.__removeAttribute(attrName);
var evt = doc.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal, "", attrName, win.MutationEvent.REMOVAL);
this.dispatchEvent(evt);
}
}
}
Related
So Google PageSpeed Insights is complaining about "Does not use passive listeners to improve scrolling performance", the complaint is more specifically about:
https://www.youtube.com/s/player/54668ca9/player_ias.vflset/en_US/base.js
and on line 5402, which would be this:
g.h.dump=function(){var a=[],b;for(b in Gr)a.push(b+"="+encodeURIComponent(String(Gr[b])));return a.join("&")};
I have my youtube video in HTML in an iframe-tag
<iframe src="https://www.youtube.com/embed/..........." width="373" height="200" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
The question is what should I do. I found the javascript code below which supposedly should resolve the issue, but I do not know where to put it. Should i put something in my functions.php-file?
The https://www.youtube.com/s/player/54668ca9/player_ias.vflset/en_US/base.js
is not a property of my domain so I do not have this js-file in my files (my Wordpress public_html), so I can not modify it.
The javascript that I found at
Wordpress and best practice with passive event listeners
and could work:
(function() {
var supportsPassive = eventListenerOptionsSupported();
if (supportsPassive) {
var addEvent = EventTarget.prototype.addEventListener;
overwriteAddEvent(addEvent);
}
function overwriteAddEvent(superMethod) {
var defaultOptions = {
passive: true,
capture: false
};
EventTarget.prototype.addEventListener = function(type, listener, options) {
var usesListenerOptions = typeof options === 'object';
var useCapture = usesListenerOptions ? options.capture : options;
options = usesListenerOptions ? options : {};
options.passive = options.passive !== undefined ? options.passive : defaultOptions.passive;
options.capture = useCapture !== undefined ? useCapture : defaultOptions.capture;
superMethod.call(this, type, listener, options);
};
}
function eventListenerOptionsSupported() {
var supported = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supported = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
return supported;
}
})();
I am using zepto for drag and swap it works perfectly in chrome but showing error in firefox. Below is the section of the script of dragswap in which it is showing error. Please help. Thanks in advance
`; (function ($) {
$.fn.dragswap = function (options) {
var dragSrcEl;
function getPrefix() {
var el = document.createElement('p'),
getPre, transforms = {
'webkitAnimation': '-webkit-animation',
'OAnimation': '-o-animation',
'msAnimation': '-ms-animation',
'MozAnimation': '-moz-animation',
'animation': 'animation'
};
document.body.insertBefore(el, null);
for (var t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = "translate3d(1px,1px,1px)";
// if(window.getComputedStyle && (style = window.getComputedStyle(element, null)) !== null)
getPre = window.getComputedStyle(el).getPropertyValue(transforms[t]);
// return the successful prefix
return t;
}
}
document.body.removeChild(el);
}
Firefox has a bug in which if the element is "display: none" then window.getComputedStyles will return null.
The below is where I found this knowledge which fixed the error in my third-party code. Note In my case the element was also an iFrame
https://github.com/marcj/css-element-queries/issues/148
This question already has an answer here:
fullscreen through javascript
(1 answer)
Closed 9 years ago.
I am looking for a way of creating a button, when clicking on it the browser should go Fullscreen. *THIS SHOULD BE BUTTON.
Please, any ideas!
I found this similar post, i guess this is the solution!
onclick go full screen But ill come back later to this question, hope someone has a new solution!
You can't. There is no way to automatically go fullscreen. Instead, you can instruct/request that your users press F11 to go fullscreen manually, but it should be optional.
well here i what I found, it works but not sure for cross-browser support!
<div id="specialstuff" style="display: none;">
</p><p>Status: <span id="fsstatus" class="fullScreenSupported">Back to normal</span></p>
</div>
<input type="button" value="Go Fullscreen" id="fsbutton">
<script>
/*
Native FullScreen JavaScript API
-------------
Assumes Mozilla naming conventions instead of W3C for now
*/
(function() {
var
fullScreenApi = {
supportsFullScreen: false,
isFullScreen: function() { return false; },
requestFullScreen: function() {},
cancelFullScreen: function() {},
fullScreenEventName: '',
prefix: ''
},
browserPrefixes = 'webkit moz o ms khtml'.split(' ');
// check for native support
if (typeof document.cancelFullScreen != 'undefined') {
fullScreenApi.supportsFullScreen = true;
} else {
// check for fullscreen support by vendor prefix
for (var i = 0, il = browserPrefixes.length; i < il; i++ ) {
fullScreenApi.prefix = browserPrefixes[i];
if (typeof document[fullScreenApi.prefix + 'CancelFullScreen' ] != 'undefined' ) {
fullScreenApi.supportsFullScreen = true;
break;
}
}
}
// update methods to do something useful
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';
fullScreenApi.isFullScreen = function() {
switch (this.prefix) {
case '':
return document.fullScreen;
case 'webkit':
return document.webkitIsFullScreen;
default:
return document[this.prefix + 'FullScreen'];
}
}
fullScreenApi.requestFullScreen = function(el) {
return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
}
fullScreenApi.cancelFullScreen = function(el) {
return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
}
}
// jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.requestFullScreen = function() {
return this.each(function() {
var el = jQuery(this);
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.requestFullScreen(el);
}
});
};
}
// export api
window.fullScreenApi = fullScreenApi;
})();
</script>
<script>
// do something interesting with fullscreen support
var fsButton = document.getElementById('fsbutton'),
fsElement = document.getElementById('specialstuff'),
fsStatus = document.getElementById('fsstatus');
if (window.fullScreenApi.supportsFullScreen) {
fsStatus.innerHTML = 'YES: Your browser supports FullScreen';
fsStatus.className = 'fullScreenSupported';
// handle button click
fsButton.addEventListener('click', function() {
window.fullScreenApi.requestFullScreen(fsElement);
}, true);
fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
fsStatus.innerHTML = 'Whoa, you went fullscreen';
} else {
fsStatus.innerHTML = 'Back to normal';
}
}, true);
} else {
fsStatus.innerHTML = 'SORRY: Your browser does not support FullScreen';
}
</script>
This code is being used on a Chrome Extension.
When I call the "showOrHideYT()" function, I get a
"Uncaught ReferenceError: showOrHideYT is not defined | (anonymous
function) | onclick"
This code will search for youtube links in a page, and it will add a button (it's really a div with an event) next to the link to show the iframe with the embedded video, pretty much like Reddit Enhancement Suite. Consider the code, per se, incomplete. I just want to know what am i missing when i call the "showOrHideYT(frameZES12345)" function.
if needed, i can provide manifest.json.
Thanks
function showOrHideYT(id)
{
var YTvidWidth = 420;
var YTvidHeight = 315;
frameYT=getElementById(id);
console.log(frameYT.style.visibility);
if (frameYT.style.visibility == "hidden")
{
frameYT.style.width = YTvidWidth+"px";
frameYT.style.height = YTvidHeight+"px";
frameYT.style.visibility = "visible";
}
if (frameYT.style.visibility == "visible")
{
frameYT.style.width = "0px";
frameYT.style.height = "0px";
frameYT.style.visibility = "hidden";
}
};
// DOM utility functions
function insertAfter( referenceNode, newNode ) {
if ((typeof(referenceNode) == 'undefined') || (referenceNode == null)) {
console.log(arguments.callee.caller);
} else if ((typeof(referenceNode.parentNode) != 'undefined') && (typeof(referenceNode.nextSibling) != 'undefined')) {
if (referenceNode.parentNode == null) {
console.log(arguments.callee.caller);
} else {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
}
};
function createElementWithID(elementType, id, classname) {
obj = document.createElement(elementType);
if (id != null) {
obj.setAttribute('id', id);
}
if ((typeof(classname) != 'undefined') && (classname != '')) {
obj.setAttribute('class', classname);
}
return obj;
};
///////////////////////////////////////
$(document).ready(function() {
var vidWidth = 420;
var vidHeight = 315;
var linksSemID = document.getElementsByTagName("a") ;
for (var i = 0; i < linksSemID.length; i++){
if (/id=$/.test(linksSemID[i].href)) links[i].href += "1";
}
i=0;
var youTubeRegExp = /(?:v=)([\w\-]+)/g;
var forEach = Array.prototype.forEach;
var linkArray = document.getElementsByTagName('a');
forEach.call(linkArray, function(link){
linkArray.id="zes" + i++;
var linkTarget = link.getAttribute('href');
if (linkTarget!=null)
{
if (linkTarget.search(youTubeRegExp) !=-1)
{
console.log (linkTarget);
idVideo=linkTarget.match(/(?:v=)([\w\-]+)/g);
//idVideo = idVideo.replace("v=", "");
//add buton
botaoMais = document.createElement('DIV');
botaoMais.setAttribute('class','expando-button collapsed video');
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
insertAfter(link, botaoMais);
//add iframe
ifrm = document.createElement('IFRAME');
ifrm.setAttribute('src', 'http://www.youtube.com/embed/'+ idVideo);
ifrm.style.width = '0px';
ifrm.style.height = '0px';
ifrm.style.frameborder='0px';
ifrm.style.visibility = 'hidden';
ifrm.setAttribute('id', 'frameZES' + i);
insertAfter(link, ifrm);
}
}
});
});
When you use setAttribute with a string, the event will be executed in the context of the page. The functions which are defined in a Content script are executed in a sandboxed scope. So, you have to pass a function reference, instead of a string:
Replace:
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
With:
botaoMais.addEventListener('click', (function(i) {
return function() {
showOrHideYT("frameZES"+ i);
};
})(i));
Explanation of code:
(function(i) { ..})(i) is used to preserve the value of i for each event.
Inside this self-invoking function, another function is returned, used as an event listener to click.
I see that you are using jQuery in your code. I personally think if we are using a library like jQuery, then we should not mix the native javascript code and jQuery code.
You can use jQuery bind to bind your the functions you need to call on dom ready.
Read below to know more.
suppose you want to call a javascript function on a button click, Here is the HTML for the same.
<div id="clickme">
<input id= "clickmebutton" type="button" value = "clickme" />
</div>
suppose "test" is the function you need to call, here is the code for test function.
function test() {
alert("hello");
}
you now need to bind the test function on the button click.
$(document).ready(function() {
$("#clickmebutton").bind("click", function(){
// do what ever you want to do here
test();
});
});
What's wrong with this code? I get "J is undefined message" after insert the image. I think this happends while i try to close itself.
var ImageDialog =
{
init : function()
{
var f = document.forms[0], ed = tinyMCEPopup.editor;
e = ed.selection.getNode();
if (e.nodeName == 'IMG')
{
f.src.value = ed.dom.getAttrib(e, 'src');
}
},
update : function()
{
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el;
tinyMCEPopup.restoreSelection();
if (f.src.value === '')
{
if (ed.selection.getNode().nodeName == 'IMG')
{
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
tinymce.extend(args,
{
src : f.src.value
});
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG')
{
ed.dom.setAttribs(el, args);
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.editor.focus();
}
else
{
ed.execCommand('mceInsertContent', false, '<img src="'+args['src']+'" id="_mce_temp_rob" alt="" />', {skip_undo : 1});
ed.undoManager.add();
ed.focus();
ed.selection.select(ed.dom.select('#_mce_temp_rob')[0]);
ed.selection.collapse(0);
ed.dom.setAttrib('_mce_temp_rob', 'id', '');
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.close();
},
getImageData : function()
{
var f = document.forms[0];
this.preloadImg = new Image();
this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value);
}
};
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
it's a tinymce bug. Internally, the tinymce code uses a <span id="mce_marker"></span> to remember the caret-position when pasting. when validating the resulting fragment, after the paste, the span is deemed invalid and removed, thus breaking the code by removing the marker.
This issue will be fixed in the next official tinymce minor release. There are some workarounds for this kind of issue. One is to add to add id and mce-data-type attribute to spans as valid elements (init setting). Example:
// The valid_elements option defines which elements will remain in the edited text when the editor saves.
valid_elements: "#[id|class|title|style]," +
"a[name|href|target|title]," +
"#p,-ol,-ul,-li,br,img[src],-sub,-sup,-b,-i,-u" +
"-span[data-mce-type]",