I am trying to detect the CSS property changes in an element. I searched online and found MutationObserver javascript API. but in my test script it is not working as expected( it's not alerting the property name and property value).
var foo = document.getElementById("hideit");
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert('mutation.type = ' + mutation.type);
});
});
observer.observe(foo);
observer.disconnect();
$(function() {
$("#clickhere").on("click", function() {
$("#hideit").slideToggle('fase');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div id="clickhere">click to toggel</div>
<div id="hideit" style="display:none;">this is the content of the hide/show toggle</div>
</body>
and it shows a javascript error
TypeError: Argument 1 of MutationObserver.observe is not an object.
Thanks is advance
There're 2 problems in your code:
usage of observer.observe is incorrect. It should take 2 params: Node and MutationObserverInit. See the correct API here.
Do not call observer.disconnect(); immediately after observe. Disconnect stops observing.
Working example
Your code is being executed before the DOM is actually being loaded... For that reason, you're passing a null/undefined value to the observe method.
Wrap your code inside:
$( document ).ready(function() {
....
})
Also calling disconnect will prevent it from receiving any event. So you shouldn't call disconnect right after calling observe. And you're missing a parameter to the observe call.
Check here for a working exemple:
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#Example_usage
Related
I have an input inside an iframe that I would like to put in a preloaded value after the page has loaded. I've put in this code so far:
<script>
jQuery('iframe').load(function(){
jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e) {
var title_name = "DO I LOOK LIKE I'M WORKING?";
jQuery('input#ysi_subject').val(title_name);
});
});
</script>
but when I look at the console log, I get this error:
Uncaught TypeError: Cannot set property 'value' of null
Can anyone help explain why it's not catching the input?
This is because you are trying to access the DOM prior to the DOM elements actually being loaded, so any references to the DOM in this case will output null. Place the code in a $(document).ready() handler in order for this to work:
... <!-- jQuery reference -->
<script>
$(document).ready(function() {
// your code that you are trying to run
});
</script>
* Note that I simplified it down to show what I am really talking about.
The change event is firing from within the iframe back to the parent window.
$("input#si_subject") does not exist in the parent window.
jQuery('iframe').load(function(){
jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e) {
var title_name = "DO I LOOK LIKE I'M WORKING?";
// this would work
jQuery('iframe').contents().find('input#ysi_subject').val(title_name);
// this is better
$(this).val(title_name);
});
});
In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>
I'm trying to use Jquery-Mutation Summary https://code.google.com/p/mutation-summary/
"a JavaScript library that makes observing changes to the DOM fast, easy and safe"
It can be found here: https://github.com/joelpurra/jquery-mutation-summary
Here's an example of it at work:
http://joelpurra.github.io/jquery-mutation-summary/example/demo.html
All I want to do is call a function when there's changes to content within an element such as a div with an id "MyDiv"
Here's my code. What am I doing wrong? There is no alert message as my function that's being called in this example is suppose to display once changes are observed.
<script src="http://joelpurra.github.io/jquery-mutation-summary/lib/mutation-summary /src/mutation-summary.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://joelpurra.github.io/jquery-mutation-summary/src/jquery.mutation- summary.js"></script>
<script>
function MyFunction(){
alert('changes have been made');
}
// This code won't be executed until jQuery has been loaded.
$(function() {
var $ChangeThere = $("#MyDiv")
// The callback in this case will only print the result
// Connect mutation-summary
$ChangeThere.mutationSummary("connect", callback, [{
all: true
}]);
// Disconnect when done listening
//$ChangeThere.mutationSummary("disconnect");
function callback(summaries) {
MyFunction();
}
});
</script>
In newer versions of Firefox, a mozAfterPaint event exists, but there's obvious compatibility problems with that, so I'd suggest checking for the various things that cause reflows by adding a check into an abstracted version of each cause. A list of causes and some other information can be found in this SO
im trying to do something here. I have a document which I set an array. Then, jquery takes this array and appends an iframe for each value:
<script>
var containers = new Array("test1", "test2");
</script>
This results is 2 iframes, identified by id with his name. Ok. perfect, working. Then, inside of each iframe, it calls a document. Inside this document, I have a function called play().
I am testing play() by returning an alert. Whenever I click on a button, it works:
$("#viewport .next").click(function(){
document.getElementById(containers[current]).contentWindow.play();
});
This works. Perfectly. But I it put this function to trigger on document ready, it doesnt works.
$(function() {
document.getElementById(containers[current]).contentWindow.play();
});
It returns to me:
Uncaught TypeError: Object [object Window] has no method 'play'
Whats am I doing wrong guys?
Thanks!
EDIT
Tried to apply onload on iframe. Didnt work.
var initialFrame = containers[qual];
initialFrame.onload = function() {
document.getElementById(initialFrame).contentWindow.play();
};
EDIT2
For some reason, it started working. Thanks!
Wait for the load event of the iframe first.
initialFrame.addEventListener("load", function() {
initialFrame.contentWindow.play();
});
You would generally listen for the iframe's load event like this:
$("#iframe").load(function(){
// iframe is loaded
});
... but I had trouble with this recently so I instead checked for the contents of the iframe over and over until it had loaded, like this:
function loadFrame() {
if($('body', $('#iframe').contents()).length != 1) {
setTimeout(loadFrame,500);
}
else {
// iframe is loaded
}
};
loadFrame();
Not sure if this is the best solution, but it works.
I have got this html:
<a style="display:block; padding:100%; text-decoration: none;" href="http://google.com " class="Jasmin" id="target_site_to_visit">
<span data-app-id="88" class="btn" id="visit_site" style="right:22px; top:65px; padding:5px;z-index: -99999;">VISIT SITE</span>
</a>
and this jquery:
(function($){
$('#target_site_to_visit').live('click',function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
throw new Error("AppName: "+appName);
},'html').error(function(data){
throw new Error("Error: "+data.responseText);
});
document.location.href=$('#target_site_to_visit').attr('href');
}); })(jQuery);
A problem exists, whenever the button is clicked.. the post method is executed which puts the data into the database. But that only happens when the last line in jquery doesnt exist: document.location.href.. the redirection effects the post somehow..and doesnt probably doesnt give the post method to execute..resulting in no record being inserted to the db (or in other post method doesnt execute).. is it possible that that is the cause..cause the redirection does effect the execution of the post method
This will solve your problem
<script type="text/javascript">
$('#target_site_to_visit').live("click",function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
// console.log("AppName: "+appName);
},'html').error(function(data){
// console.log("Error: "+data.responseText);
});
// document.location.href=$('#target_site_to_visit').attr('href');
});
But use .on() instead of .live().LIke
<script type="text/javascript">
$(document).on("click",'#target_site_to_visit',function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
// console.log("AppName: "+appName);
},'html').error(function(data){
// console.log("Error: "+data.responseText);
});
// document.location.href=$('#target_site_to_visit').attr('href');
});
</script>
You need to pass the event to listen for (in this case click) to the live method.
$("#somediv").live("click", function () {
console.log("you clicked it");
});
Also, as the other answerer said, you should use on as opposed to live, here is an article that explains why: http://bitovi.com/blog/2011/04/why-you-should-never-use-jquery-live.html
You don't appear to have specified the type of event. It should be 'click', and if my extremely limited knowledge of jQuery syntax is correct, it should be the first parameter before your callback.
To be on the safe side, I like to have any link that is intended to be handled by JavaScript have href="javascript:void(null);". That way, even if the event handler fails to cancel the event, nothing will happen anyway. It's also less confusing for the users to see a JavaScript link in their status bar when you hover over it, than a link to Google.