checking class not returning true - javascript

I want to check if my #pax div has class named .is-show I made function to check with if statement but it doesn't work any help will be appericated.
function yle() {
var le = document.querySelector("#pax");
if (le.classList.contains("is-shown")) {
alert("hello");
}
}
yle();
<div id="pax" class="p-section--03 is-shown">

You should add your script tag after the DOM elements, this may be a cause where DOM is not loaded and your script is running first, Hence unable to find your elements.
<html>
<div id="pax" class="p-section--03 is-shown"></div>
<script>
function yle() {
var le = document.querySelector("#pax");
if (le.classList.contains("is-shown")) {
alert("hello");
}
}
yle();
</script>
</html>
Else everything is fine, Thanks.

Related

Waiting with $(document).ready, $(element).ready, and windows.load all trigger before content is ready

Would you please help me delay execution of my function until the content has loaded? I've streamlined my code to the essentials, bear with my typos:
function Phase1()
{
$(".Hidden").load("hidden.html");
$(window).load(Phase2());
/* I've also tried $(document).ready(Phase2()); */
/* and $(."Hidden").load("hidden.html",Phase2()); */
/* and window.onload... */
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
The Random class contains several items. On the first pass the alerts are never called (length is 0), on the 2nd iteration it's had time to load everything.
I see no errors in the console when executing.
I have a small and neat solution for your problem, all you need to do is,
Call a setInterval for very short span to check the element is present in DOM or not, if its not your interval will go on, once the element is present, trigger your functions and clear that interval.
code will look like this..
var storeTimeInterval = setInterval(function() {
if (jQuery('.yourClass').length > 0) {
//do your stuff here..... and then clear the interval in next line
clearInterval(storeTimeInterval);
}
}, 100);
The page will load the elements from top to bottom.
If you want your JS code to execute after all elements have loaded, you may try any of the following:
Move your script to the bottom of the page.
<html>
<head></head>
<body>
<!-- Your HTML elements here -->
<script>
// Declaring your functions
function Phase1()
{
$(".Hidden").load("hidden.html");
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
// Executing your functions in that order.
Phase1();
Phase2();
</script>
</body>
</html>
Bind your functions to document ready using Vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
Phase1();
Phase2();
});
Bind your functions to document using jQuery.
$(document).ready(function() {
Phase1();
Phase2();
});

Use JavaScript to go to a page and automatically do a function on that page

Hopefully this is a no-brainer for all you experts, but I can't find the answer. I want to click on an element on Page A that will take me to Page B and automatically perform a function (here it's called showGrp) defined on Page B. On Page A, I want to click something like this (obviously, it doesn't work, but I think it conveys the idea):
<span onclick="location.assign('http://happy.com/pageB.htm').('showGrp(); return false;')">
<h2>Search Topics</h2>
</span>`
Short answer: there's no way to do that. You can't tell a new page to run a function through an old page
Long answer: You can, however, set up page B so it will know that if the request URL contains a certain argument in its GET data, it will run showGrp. i.e.:
going to http://happy.com/pageB.htm will do nothing
going to http://happy.com/pageB.htm?showGrp=1 will run function
You can use this function like so:
// put this wherever you want to run this - most probably when the page is loaded
if (getParameterByName('showGrp')) {
showGrp();
}
You could do something like this:
PageA:
<html>
<body>
<a href="pageB.html?f=showGrp">
<h2>Search Topics</h2>
</a>
</body>
</html>
PageB:
<html>
<head>
<script type="text/javascript">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
var init = {
showGrp: function () {
console.log("Hello world!");
},
otherFunc: function() {
console.log("Lalala!");
}
};
init[getQueryVariable("f")]();
</script>
</head>
</html>
By making this you are able to execute whatever function you want just passing it name as an argument to the pageB's URL.
I would just put the code that you want to run in the window onload function on page B. I think that will do what you want.
window.onload = function() {
showGrp();
};
See a description of onload at the Mozilla Developers Network.
Page A should look like:
<div id = "yourclickobject" onclick="pageB.html"> Some random text </div>
Page B:
<head>
<script>
var myFunction = function(){
alert("hello world");
}
myFunction();
</script>
</head>
Does this help?
As soon as you go on page B myFunction is called. All you need to do is put it in the head

Have the element who call my js function

I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}

jQuery + Module Pattern: When to declare/query elements?

Typically, you don't start querying the DOM until the $(document).ready().
In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
Would it be better to put this whole Widget definition inside the $(document).ready()?
Should I wait until the Widget.init() to query the elements?
Note: I'm brand new to JS design patterns, so please note if I'm missing something
Option1
Widget = {
ele : $('#ele'),
init : function(){ ... }
};
$(document).ready(function(){
Widget.init();
});
Option2
Widget = (function(){
var privateEle = $('#privateEle');
return {
publicEle: $('#publicEle'),
init: function(){ ... }
};
}());
$(document).ready(function(){
Widget.init();
});
What I would do:
var Widget = (function(){
var ele;
function init(_ele){
ele = _ele;
};
return {
init: init
};
})();
$(function(){
Widget.init( $('#foo') );
});
If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []
EDIT: btw.. put your <script> tags before </body> NOT within <head></head>
It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.
what would work though is on of the following:
create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.
Widget = {
ele : $("<div id='ele'>"),
....
}
or you can query the element on widget initialization.
Widget = {
ele : "#ele",
init : function(){
this.ele = $(this.ele);
...
}
}
You can include script just before body end tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<!-- my HTML -->
<script src="../js/vendor/jquery-1.9.1.js"></script>
<script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
<script src="../js/custom.js"></script>
</body>
</html>
DOM is ready (no need for $(document).ready):
/*custom.js */
var Widget = (function($){
var _$element;
return {
init: function(){
_$element = $('#myElementId');
// TODO - element is available from now on
};
};
}(jQuery));
Widget.init();

Javascript: Check if page contains a particular div

How do I check using javascript if the page I'm on contains a particular div... e.g turtles
if(document.getElementById("divid")!=null){
alert('Div exists')
}
if you have that div's id, you can do it that way:
var myDiv = document.getElementById( 'turtles' );
if ( myDiv ) {
//It exists
}
overwise, if it's a class, you'd better use a framework (jQuery here):
if ( $('.turtles').length > 0 ) {
//it exists
}
Like this:
<script type="text/javascript">
function CheckExists() {
var oDiv = document.getElementById("turtles");
if (oDiv) {
alert("exists");
}
else {
alert("does not exist");
}
}
</script>
The function must be located in bottom of page or called after page finished loading.
I'd just like to point out that document.contains is another way to do this.
document.contains is particularly useful if you have a web application whose components are rendered virtually before insertion into the DOM.

Categories

Resources