Can't trigger the close button click event from the Menu - javascript

I have this burger menu which I can't invoke the button onclick event function when I click it.
HTML code:
<button class="nav-aside-close"><i class="fa fa-times"></i></button>
JQuery code:
$('.nav-aside-close').on('click', function () {
console.log('test');
$('#nav-aside').removeClass('active');
$('#nav').removeClass('shadow-active');
});
If I click any area outside the burger menu, it works. Below is the code which works:
$(document).click(function(event) {
if (!$(event.target).closest($('#nav-aside')).length) {
if ($('#nav-aside').hasClass('active')) {
$('#nav-aside').removeClass('active');
$('#nav').removeClass('shadow-active');
} else {
if ($(event.target).closest('.aside-btn').length) {
$('#nav-aside').addClass('active');
$('#nav').addClass('shadow-active');
}
}
}
});
Actual code I have uploaded it at http://js.findingsteve.net

If you're using Chrome, open up DevTools (F12) and do this on the Console tab and hit Enter:
getEventListeners(document.querySelector('button.nav-aside-close'))
If you see any click events registered, it should work.
Anyway, I noticed you are putting the main.js file on the <head> and not using jQuery.ready, so your click handler is essentially never attached since the DOM element is not ready by the time the script executes.
Solution:
Add the jQuery alias $ on the very first line of your JS file, that is a shorthand for jQuery.ready BTW.
$(function($) {
"use strict"
// Fixed Nav
var lastScrollTop = 0;
Don't forget to also remove the jQuery function assignment from the end of the line, since it's no longer an IIFE.
setStickyPos();
})(jQuery);
Alternative, you can keep everything as is and move your main.js file to the <body> element, right before the closing </body> tag. That is pretty much the same as having the scripts executed when all the elements above it have finished loading.

It's probably because .nav-aside-close is hidden in the initial render.
Try this instead:
$("#nav").on("click", ".nav-aside-close", function() {
$("#nav-aside").removeClass("active");
$("#nav").removeClass("shadow-active");
});

Based in #Ana Liza Pandac comment
It should be:
$("#nav").on("click", "#nav-aside .nav-aside-close", function() {
$("#nav-aside").removeClass("active");
$("#nav").removeClass("shadow-active");
});
Your tree is: nav->nav-aside and obj with class nav-aside-close
The difference is on:
$("#nav").on("click", "#nav-aside .nav-aside-close", function()

Related

Script to change animation play state

If i put some script in HTML file to change the animation play state,it's works.But when i put the script in a script file,it's not working.Can anyone tell me why?
script like this:
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
The elements may not be defined in document. Try placing the existing script within load event handler of window
function toggleAnimationPlayState() {
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
}
window.addEventListener("load", toggleAnimationPlayState);
Your script dependens on the existing of this Button :
=document.getElementsByTagName("button");
So,
it works because the script has been running after rendering the button .
It does not work because either :
Fail to import script. (check browser's console)
OR
Import the script BEFORE rendering the button .
Solution :
follow this order .
<button>....</button>
.......
<script src="/uri/of/script.js"></script>
OR, run your code inside onload listner of window

How to make specific click trigger link else do something else?

I am doing this for a "welcome dialog".
This function listens if you click on specific <div> and sends you to another web page or closes the welcome <div>.
But I think I couldn't make it work for the "close" functionality.
My script in the HTML head:
function hideWell() {
if (("welSolu").on('click hover')) {
location.href = "http://www.cnn.com";
}
document.getElementById("welScreen").style.visibility = "hidden";
document.getElementById("welScreen").style.display = "none";
document.querySelector("html").style.overflow = "visible";
}
My <div>s in the HTML body:
<div id="welScreen" onmousedown="hideWell()">
<div id="welSolu">to go another page click here</div>
</div>
I suggest you to use two different functions for that, because it is a good practice that one function does one thing. Event your code has several mistakes, without jquery you can do your thing like this:
function doRedirect(e) {
// Prevent event propagation to the outer div
e.stopPropagation();
// Do your redirect
console.info("redirect");
}
function hideWell(e) {
// Do the hiding thing
console.info("hideWell");
}
#welScreen {
padding: 15px;
background: gray;
}
#welSolu {
background: green;
}
<div id="welScreen" onmousedown="hideWell(event)">
<div id="welSolu" onmousedown="doRedirect(event)">to go another page click here</div>
</div>
There is no need to attach a function to the onmousedown event. Just set up event listeners for whatever you want. I'm not entirely sure when you want to hide the welcome div, but something like this should work:
$('#welSolu').click(function() {
location.href = "http://www.cnn.com";
});
$('#welScreen').click(function() {
this.hide();
});
HTML:
<div id="welScreen">
<div id="welSolu">to go another page click here</div>
</div>
The problem in your code is in the if clause - the on() method in JQuery uses callback mechanism - its not something you call to "check the status", instead you use it to "register for status change notifications".
So something like this is the intended behavior:
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
(although changing the current page when someone hovers over an element in the page is really disruptive, please don't do that).
This code shouldn't be inside the hideWell() function - it should be run as part of the ready state handling of your page - i.e. it should be run immediately as the "document becomes ready" but not before that. JQuery has a facility for that, which would look something like this:
$(document).ready(function(){
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
});
The other part of the function can stay the same as it is and it will get activated as you expect when the user "mouses down" on the part of the div that wasn't handled by the JQuery event handler - though it is likely a good idea to also change that to use JQuery event handling, just to make all the code use the same mechanism: its easier to understand and maintain that way.
So the full replacement code might looks like this:
Script in HEAD:
$(document).ready(function() {
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
$("#welScreen").on('click', function() {
document.getElementById("welScreen").style.visibility = "hidden";
document.getElementById("welScreen").style.display = "none";
document.querySelector("html").style.overflow = "visible";
});
}

Selector only working after inspecting/selecting element

I have this code here:
$(document).ready(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('Hello'); });
});
The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []
But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.
I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.
$(document).ready(function() {
//debugger;
setTimeout(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('allo'); });
}, 10000);
});
Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?
I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.
The reason it works when you inspect an element, is Chrome has selected the execution context for you already.
Discussion about iFrame context in Dev Tools
Using the "on", it works even if the element exists after the page loads.
$(document).ready(function(){
//$("div[id^='stage_']").click( function (e) { alert('Hello'); });
$("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
$('body').html('<div id="stage_1">teste1</div>' +
'<div id="stage_2">teste2</div>' +
'<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc: http://api.jquery.com/on/

OnClick works only works after reload, using jquerymobile

I know it's an often asked question, but no answer (till now) fits for me.
I wrote a mobile app with Cordova. I'm also testing apps in browser (Firefox). I'm using jQuery and jq mobile.
The problem is: my OnClick events on work only after refresh, which isn't possible on mobile and even on pc not really an solution.
Update: I read about, that the ehader isn't loaded again in jQuery mobile. So I treid it as described in thsi solution: page loaded differently with jQuery-mobile transition
didn't work.
And with alert(); you see, that the script runs once but before the site is totally build.
My html:
<div data-role="main" class="ui-content" id="container" >
<div id="container0">
<a data-role="button" id="anchor0" >Neuen Termin Hinzufügen</a>
</div>
</div>
originally the <a> had an onclick (<a onClick>="doStuff()")
Here a are my different attempts:
$(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
});
$(document).ready($(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
})
);
$("#anchor0").live("click", dateElementClicked($("#anchor0")));
$("a").click( dateElementClicked(this));
$("a").bind("click", function (event, ui){
dateElementClicked(this);
});
They all work only after an refresh. or the first one runs the function instant and interupts everything because "this" is undefined.
Edit:
I even tried it with button and inpute type button and made extra js file. but my javascript only runs after an refresh... Putted an console log and alert in the script. So the whole script is stuck somehow
The dateelement clicked function (I cleared this too for testing and just put an alert() in it)
Here is the git link to the project: https://github.com/LosKartoflos/Apoll.git
function dateElementClicked(clickedAnchor) {
//anchor is clicked the first time(the id number equals numberOfAppointments)
if (clickedAnchor.id.slice(-1) == numberOfAppointments) {
dateElementClickedFirstTime(clickedAnchor);
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == true)
{
hideContent(getDateElementNumber(clickedAnchor));
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == false)
{
showContent(getDateElementNumber(clickedAnchor));
}
else
{
alert("Element not listed");
}
}
BTW: my script isin my html file.
Maybe try using the deviceready event instead of document ready.
https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
Try this
$(document).on('click', '#anchor0', function(event) {
});
or this
$(document).on('click', 'a', function(event) {
});
okay the Problem is, that Cordova is messing around with normal build/loading oder. to trigger functions, after the side is loaded.
The Cordova Documentary recommends this two solutions:
Put this in your header and bind your events in the onload or dofirst. An do everything you want to be have done, after page is ready, in the do first:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/script.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//add all Events (click Events)
function onLoad() {
document.addEventListener("deviceready", doFirst(), false);
document.getElementById("anchor").addEventListener("click", clickedFunction, false);
}
// device APIs are available
function onDeviceReady() {
}
//things to put up first
function doFirst() {
}
</script>
or put it in the onDeviceReady function, in the auto created index.js .
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
document.getElementById("anchor0").addEventListener("click", clicked, false);
app.receivedEvent('deviceready');
},
Here the documentary: https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
And i kicked out jquery and jquery mobile. Jquery was messing around with document ready and jquery mobile prevents the head from beeing loaded again.

simulating a click on a <a>-element in javascript

for a website, i am using the jQuery supzersized gallery script: http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
As you can see in the demo, in the bottom right corner there is an little arrow button that toggles a thumbnail bar. There is no option in the config files to automatically blend this in when opening the site.
So i guess i have to simulate a click on that button (the button is the tray-button, see HTML). I tried something like this:
<script>
$(function() {
$('#tray-button').click();
});
</script>
However, this doesnt seem to work in any browsers i tested.
Any idea?
$('#tray-arrow').click(function() {
// prepare an action here, maybe say goodbye.
//
// if #tray-arrow is button or link <a href=...>
// you can allow or disallow going to the link:
// return true; // accept action
// return false; // disallow
});
$('#tray-arrow').trigger('click'); // this is a simulation of click
Try this
$("#tray-arrow").live("click", function () {
// do something
});
I assume that you want to popup the thumbnail bar #thump-tray on page load.
Here's a way to do it:
locate the file supersized.shutter.js and find this code:
// Thumbnail Tray Toggle
$(vars.tray_button).toggle(function(){
$(vars.thumb_tray).stop().animate({bottom : 0, avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-down.png");
return false;
}, function() {
$(vars.thumb_tray).stop().animate({bottom : -$(vars.thumb_tray).height(), avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-up.png");
return false;
});
After it, add:
$(vars.tray_button).click();
Dont forget in your page (demo.html in the plugin), to change
<script type="text/javascript" src="theme/supersized.shutter.min.js"></script>
to
<script type="text/javascript" src="theme/supersized.shutter.js"></script>
instead of using
$(function(){
//jquery magic magic
});
you culd try this witch will work your jquery magic after the full page is loaded (images etc)
$(window).load(function () {
// jquery magic
});
and to simulate a click you culd use // shuld be the same as $('#tray-arrow').click();
$('#tray-arrow').trigger('click',function(){ })
example:
$(window).load(function () {
$('#tray-arrow').trigger('click',function(){
alert('just been clicked!');
})
});
try
<script>
$(function() {
$('#tray-arrow').click();
});
</script>
Make sure that this code is after your carousel is initialized.
This looks like it's a problem of timing the trigger. The plugin also loads on document load, so maybe when you try to bind the event listener the element is not created yet.
Maybe you need to add the listener in something like the theme._init function
http://buildinternet.com/project/supersized/docs.html#theme-init
or somewhere similar.
A problem might be that your plugin detects whether the click has been initiated by a user (real mouse click), or through code (by using $('#id').click() method). If so, it's natural that you can't get any result from clicking the anchor element through code.
Check the source code of your plugin.

Categories

Resources