Jquery function - on element - javascript

I have this jquery code, working 100%.
This is executing on every page load, when i import my js file in the html.
My question, how can i make use of this code, only when the element is present, or call it directly from the element itself? I have similiar functions, but, on html's that dont have specific elements, javascript execution halts. Sometimes because the html elements dont exist on that specific html file.
/**
* Message Box Display
*/
$(document).ready(function() {
$("#Message-Box" ).slideDown("slow", function() {
$("#Message-Box").addClass('Show');
setTimeout(function(){
$('#Message-Box').addClass('Hide');
}, 5000);
});
});

try something like this
$(document).ready(function() {
var msgbx = $("#Message-Box");
if (msgbx.length) {
msgbx.slideDown("slow", function() {
msgbx.addClass('Show');
setTimeout(function() {
msgbx.addClass('Hide');
}, 5000);
});
}
});

The function halting my script was this one:
/**
* Background-Audio
*/
$(document).ready(function() {
var audioTrack = document.getElementById("Background-Audio");
if(audioTrack)
{
audioTrack.volume = 0.05;
audioTrack.play();
}
});

Related

Call user defined jQuery function with JS

I use a jQuery window libray https://github.com/humaan/Modaal
which triggers events this way $("class of element").modaal({arg1, arg2,...});
--- I updated my question here to make it more general and used an iframe / Html instead of an external svg ---
To trigger an element e.g. in an external Html which is loaded within an iframe, I applied the following code to the iframe:
<iframe src="External.html" id="mainContent" onload="access()"></iframe>
which calls this function:
function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}
Actually it will only work on every second click. Any idea what I did not consider properly?
Best
You do not need to wait windows loading but iframe only:
$(function() {
$("#mainContent").bind("load",function(){
var myIframeElement = $(this).contents().find(".modaal");
myIframeElement.modaal({
content_source: '#iframe-content',
type: 'inline',
});
});
});
The reason why it did not work was that the iframe was not completely loaded, while jQuery tried to attach the function. As $(document).ready(function(){} did not work, the workaround was to initialize it with
$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});
This worked properly to attach the functionallity to an element within the iframe.
Actually modaal will vanish the envent handler after the overlay was opened and closed again.
So maybe someone wants to trigger an iframe element for modaal, too, here is a setup which would solve this issue.
(It can be optimised by #SvenLiivaks answer):
$(window).on("load", function() {
reload();
});
function reload() {
var length = $("#iframeID").contents().find("#IDofDIVelement").length;
// The following check will return 1, as the iframe exists.
if (length == 0) {
setTimeout(function() { reload() }, 500);
} else {
$("#iframeID").contents().find("#IDofDIVelement").modaal({
content_source: '#modalwrapper',
overlay_close: true,
after_close: function reattach() {
reload();
}
});
}
}

<div> value not updating in html page

I am using jquery to auto update a part of the HTML page. Following is the code
$(document).ready( function() {
$('#auto').load("static/l.txt");
refresh();
});
function refresh() {
setTimeout(function() {
$('#auto').load("static/l.txt");
refresh();
}, 1000);
}
The id of the HTML div tag to be updated is auto
The file static/l.txt is continuously being updated by another python program.
But when I load the html page , the div only gets updated once and does not update the value until and unless I open the developers console on the browser.
I am hosting the web page using Flask in python
How about trying this?
var counter =0 ;
$(document).ready( function() {
$('#auto').val("starting");
refresh();
});
function refresh() {
setInterval( function() {
counter ++;
$('#auto').val(counter);
}, 1000);
}
Use a callback to know, when the content is actually loaded and move the function definition in the ready block, also.
$(document).ready(function() {
function loadData() {
$('#auto').load('static/l.txt', function(completed) {
setTimeout(loadData, 1000);
});
}
loadData();
});

Document ready function - Not loading the code first

I have a function that works on the body onload="" but I need it to load before other elements of the page and I'm trying to add the document ready function in the header but it just doesn't seem to work.
f1menu() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
}
$(document).ready(function() {
f1menu();
});
So the onload function that works is just this one below:
onload="$('.menuH').hover(function() {$('.menuC').stop().animate({width: '90px'}, 333)}, function() {$('.menuC').stop().animate({width: '-0'}, 333)});"
Note that the following answer was provided before the OP changed the question.
You should write:
function f1menu(){}
not,
f1menu(){}
In addition, you can streamline your document.ready code by simply passing the function that you want called when the document is ready, directly to jQuery:
$(function() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'}, 333);
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333);
}
);
});
UPDATE:
After OP revised the question, the solution (not a recommended approach by the way) would be to just insert the script into the body of the page, but AFTER any elements that the function references, such as:
<body>
<!-- elements that the code references must come before the code -->
<script>
// .menuH and .menuC elements must have already been loaded into DOM
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
</script>
<!-- Rest of HTML -->
</body>
It doesnt know f1menu is a function since you didnt declare it as one. Try this:
function f1menu(){
//logic
}

How to find JS function name?

I have implemented on a website a picture gallery that does not allow (it seems) the auto sliding. So at the moment I have to push on a button to see the next picture. My purpose is to catch the function that allows to move to the next picture and to set a timeout to go to the next picture automatically.
How can I get the JS function name using Google Chrome developer tools?
Thank you
UPDATE
This is the Gallery script: http://tympanus.net/Development/ScatteredPolaroidsGallery/
I would like to implement auto sliding on it
source for code proposal from: https://github.com/codrops/ScatteredPolaroidsGallery/issues/4
(function() {
function autoSliding(timeout) {
var self = this;
clearTimeout(self.timeOut);
self.timeOut = setTimeout(function() {
self._navigate('next');
}, timeout);
}
new Photostack( document.getElementById( 'photostack-1' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
new Photostack( document.getElementById( 'photostack-2' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
}())
This should do the work
$('.navigate-next').click();
Or for auto scroll
setInterval(function(){$('.navigate-next').click();},1000);
Change 1000 for whatever you wish
If you are allowed to use jquery in your code, then, you can use $._data() method.
syntax is $._data($("selector of the element")[0], "events")
This will return an Object of all events bounded to that element. Then get the click event and call the handler attribute of the click event.

How can i add $(document).ready(function(){}) after a function in java script

What I want to do is I have a code like below :
$(document).ready(
function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
}
)
And now I want to add this code to add and get work with other code. I need to add this code after this one:
function () {
/* If there are forms, make all the submit buttons in the page appear
disabled and prevent them to be submitted again to avoid accidental
double clicking. See Issue 980. */
jQuery(function() {
/* Delegate the function to document so it's likely to be the last event
in the queue because of event bubbling. */
jQuery(document).delegate("form", "submit", function (e) {
var form = jQuery(this);
if (form.hasClass("form_disabled")) {
e.preventDefault();
return false;
}
else {
form
.addClass("form_disabled")
.find(":submit")
.addClass("disabled");
}
// Reactivate the forms and their buttons after 3 secs as a fallback.
setTimeout(function () {
form
.removeClass("form_disabled")
.find(":submit")
.removeClass("disabled");
}, 3000);
});
});
}
How can I get this done. Please help me out to solve this problem.
You can create document.ready() anywhere in script. It is not necessary all of your code should be in ready function.
You can create instance variable for function and call it where you need:
$(document).ready(
var myFunc = function(){
var currentPage = window.location.pathname;
//other code
}
...
//and invoke it where you need
myFunc();
)
First, name the long function in your code section, for example, launchFormControls(). And then define the function outside of the document ready event. A good practice would be to do so and keep the ready event body clean.
For example:
function launchFormControls() {
//function code
}
Or, in other syntax:
var launchFormControls = function() {
//function code
}
Second, call your function from within the document ready event. Your function will be defined and able to call once the document is loaded. This code can be placed at the top or bottom of your javascript section or file.
For example:
$(document).ready(function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');
launchFormControls();
});

Categories