why do my onClick functions take two clicks - javascript

I've noticed from a few different projects of mine that whenever I click something I add an onClick function to, it always takes two clicks to get them going when a page is freshly loaded. The general structure I use for them is:
function PageChange(){
var welc_p = document.getElementById("welcome");/**gathers page DIVs**/
var page01 = document.getElementById("page01");
var page02 = document.getElementById("page02");
var start = document.getElementById("start_btn");/**gathers buttons**/
var p1_back = document.getElementById("p1_back");
var p1_next = document.getElementById("p1_back");
var p2_back = document.getElementById("p2_back");
var p2_next = document.getElementById("p2_back");
start.onclick=function(){
page01.style.display="block";
welc_p.style.display="none";
window.location="#page01";
};
}/**function**/
then the way I call it in the html is
<div class="some_class" id="start_btn" onClick="PageChange()">!!!LETS GET STARTED!!!</div>
Here's a fiddle of it as well.
https://jsfiddle.net/Optiq/42e3juta/
this is generally how I structure it each time I want to create this functionality. I've seen tons of other posts on here about their items taking 2 clicks to activate but none of them were doing anything near what I was trying to accomplish and it seemed their problem was within their coding. Does anybody know why this is happening?

This is because you are attatching a event handler to your button on click of your button.
This means that one click of the button activates the event handler, not the code within start.onclick=function() {
Then, the second click works becasue the event handler has been activated, and now the code will run.
Try moving your code out of the function, then it will work with just one click

Just had the same issue, and found an easy solution based on the above answer.
Since your function needs two clicks to work, I just called the function above the function and it works fine. This way the function already gets called one time on load, then it gets called the second time when you click it.
yourFunction();
function yourFunction(){
-- content --
}

I also had the same 2 clicks required on intitial interaction and after many searches couldn't find the best solution for my specific nav menu. I tried this solution above but couldn't get it to work.
Stumbled upon this code from a youtube example and it solved my issue. I wanted to nest submenu's for multiple levels and modified it from its original implementation to work best for my responsive mobile menu.
var a;
function toggleFirstLevelMobileSubMenu(){
if(a==1){
document.getElementById("mobile-sub-menu-depth-1").style.display="none";
return a=0;
}
else {
document.getElementById("mobile-sub-menu-depth-1").style.display="flex";
return a=1;
}
}
var b;
function toggleSecondLevelMobileSubMenu(){
if(b==1){
document.getElementById("mobile-sub-menu-depth-2").style.display="none";
return b=0;
}
else {
document.getElementById("mobile-sub-menu-depth-2").style.display="flex";
return b=1;
}
}
Of course, in the CSS I had display: none set for both ID's.

First, the problem:- On first click instead of running js your browser runs the button aka the event.
Solution:- in order to resolve this we need to make sure our function is already before the event is run (this is one of the ways to solve the problem). To achive this we need to load the function aka call the function in some way.
So, i just simply called the function after function is completed.
Code answer-
Just add at the end of your code
PageChange();

Related

Delete a single URL from a chrome-extension popup-window seems not working with adding event listeners (the event listener might be scoped?)

Background information
I am trying to make a functional chrome-extension popup-window that enables the user to add links (based on the open tab's URL) when he desires it, and deletes one link or delete all of the links in just one click. Down below are all of my files! I must say in advance that I am not very good (and not experienced) with using jQuery's library but if that's the only solution that I have, than I will use it in my code.
The problem
The buttons to delete all the links and the button to add one link does work perfectly without bugs. However, the button to which one link should be deleted doesn't work, I tried various ways including splicing. I am trying to remove the link from the DOM and from the chrome.storage.local, both actions do not work. In the following code you can see all of the files I have thus far. The code of when the 'X' button is pressed doesn't get executed (see these pictures): https://i.stack.imgur.com/gg1Dy.png and https://i.stack.imgur.com/4oGdI.png
The code
manifest.json:
gist.github.com/kobrajunior/78acda830c2d1c384333542422f1494d
popup.js:
functions to look at: addToDom and removeMe and the very first event listener when the DOM is fully loaded
gist.github.com/kobrajunior/4852f85ae18cfb9edbe542a820b8c107
For extra information (if needed), the popup.html:
gist.github.com/kobrajunior/1c26691734c19391c62dc336ed2e1791
Thank you in advance.
For the following lines in popup.js, you want to restore (show all the items/buttons) and bind listeners, however don't forget addToDom is called inside the callback of chrome.storage.local.get, that means by the time you assign value to allButtons, they're not added to DOM, that causes allButtons.length === 0 and you didn't bind anything in fact.
Try to move the binding logic inside the callback of restore (You may encounter other issues however that's not covered in this quesions).
document.addEventListener('DOMContentLoaded', function () {
restore();
var allButtons = document.getElementsByClassName('buttons');
function listenI(i) {
allButtons[i].addEventListener('click', () => removeMe(i));
}
for (var i = 0; i < allButtons.length; i++) {
listenI(i);
}
});
function restore() {
// get the tab link and title
chrome.storage.local.get({ urlList: [], titleList: [] }, function (data) {
urlList = data.urlList;
titleList = data.titleList;
// add the titles and url's to the DOM
for (var i = 0, n = urlList.length; i < n; i++) {
addToDom(urlList[i], titleList[i]);
}
});
}

Running function on window scroll once in jQuery

I'm creating my portfolio and I'm trying to make my skill bars load when I go to "My skills" section. I want them to do it only once, either when someone scroll to this section or goes to it straight away from the navigation. This is my code:
var skills = $('#mySkills');
var skillsPositionTop = skills.position().top;
$(window).on("resize scroll", function (){
if (pageYOffset<skillsPositionTop-20 && pageYOffset>skillsPositionTop-80){
console.log ("here is my loading script");
}
});
It doesn't work when I use one instead of on, doesn't work when I created one more function on window with one inside my if statement.
I was trying exit the function with return or return false as well and here, on stack overflow I found something about flag, which I didn't fully understand but I tried different combinations with it.
Can someone please help me with it? I've seen there is a library for this type of effects, but there is no point of installing any just for one thing...
Edit. Console.log represens my loading code.
You can set a namespace at .on() for resize, scroll events, use .off() within if statement to remove namespaced events.
var skills = $('#mySkills');
var skillsPositionTop = skills.position().top;
$(window).on("resize.once scroll.once", function (){
if (pageYOffset<skillsPositionTop-20 && pageYOffset>skillsPositionTop-80) {
$(this).off("resize.once").off("scroll.once");
console.log ("here is my loading script");
}
});

Sitecore 8 Speak UI - Call Pagecode Javascript from HTMLTemplate link

I am working on ListControl and one of the columns has Delete link which I am formatting using HTMLTemplate as follows:
<a href="javascript: app.showConfirmation()" >Delete</a>
My Javascript looks as follows:
define(["sitecore", function (Sitecore) {
var DestinationRules = Sitecore.Definitions.App.extend({
initialized: function () {
this.processDestinationRules();
},
showConfirmation: function () {
alert('here');
},
});
return DestinationRules;
});
For some reason, I am not able to call showConfirmation(). It says is undefined. I even tried Sitecore.Speak.app.showconfirmation() but not working.
I tried my best to search online but not able to find much help around calling function through controls embedded inside HTMLTemplate.
My next step is to call DialogWindow.
Please if you can help me with the syntax of the above. Thanks in advance.
Fixed it in a different way.
I wanted to show in-line Delete button in each row of the Listcontrol. Could not figure out way to call the
javascript: app.showConfirmation()
I changed the way to delete the record:
Have one Delete button outside the ListControl.
Enable/Disable the Delete button based on binding ListControl.HasSelectedItem.
On click of the Delete button, call showConfirmation()
As of now seems to be a better way. Sitecore itself uses similar approach for "Kicking off" users. Can be found here:
/sitecore/client/Applications/LicenseOptions/KickUser
Hope that helps. Thanks.
Finally, managed to do this. Always knew that it can be done this way but did not like the way its done.
The Delete link in List control opens up a confirmation Dialogue window. And if user selects Yes then it calls the app.onDeleteYes()
The HtmlMarkup for the column:
Delete
Added a button called btnDelete with visibility set to false.
Added following function, outside the scope of App:
var destinationRulePage = (function () {
var self = this;
self.showDeleteDialog = function (id) {
$("button[data-sc-id='btnYes']").attr("data-sc-click",
"javascript:app.onDeleteYes(" + id + ");");
$("button[data-sc-id='btnDelete']").click();
}
return self;
}())
This does the job for me. Thanks.

How to create a global function that closes a jQuery colorbox?

First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me).
I tried to create the function
closepan() {
$.colorbox.close();
}
first case : inside the
$(document).ready(function(){...});
but then I got the error closepan is undefined.
second case : before the
$(document).ready(function(){...});
but then it's the colorbox method that is undefined!
I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working!
In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button?
No matter where you create a variable or function if you create it on window it will be available globally.
window.closepan = function() {
// hello there
}
function closepan() {
if($.colorbox) {
$.colorbox.close();
}
}
However, at the point where someone clicks your button all external scripts should have been loaded so that check shouldn't be necessary...
Don't forget to put the keyword function in front of your declaration...
function closepan() {
$.colorbox.close();
}
Working JSFiddle

Javascript anonymous functions sync

Simply put I'm trying to sync two slideshows created using widgetkit lib in a joomla website, eg. when user clicks next slide on one, the other one also runs nextSlide() function in the slideshow.js. Same for previous. The problems I'm having is widgetkit uses anonymous functions for creating those slideshows and I dont have global references to them after they are created. With my limited programming knowledge I cant seem to trigger the nextSlide function for other slideshows once inside click handler.
If anyone can take a look it would be most welcome.
EDIT:
Of course I forgot to link the example webpage
http://www.yootheme.com/widgetkit/examples/slideshow
Mine is similar with only 2 slideshows, but is still only on local server.
Taking a brief look at widgetkit here is one possible solution. Using jquery you can search for any objects that have a class of slides with a child of next and click all others. The code provided below isn't tested but should point you in the right direction. As long as you don't call stop propagation or prevent default then the original click handlers should still fire.
var slideshow_count = $('.slides .next').length;
var cascade_countdown = 0;
$('.slides .next').each(function() {
$(this).click(function() {
// stop an infinite loop if we're already cascading till we've done it for all the elements.
if(cascade_countdown != 0) {
cascade_countdown--;
return true;
}
// we don't include the slideshow we're clicking in this count
cascade_countdown = slideshow_count - 1;
var clicked_el = this;
$('.slides .next').each(function() {
// only click elements that aren't the initiator
if(this !== clicked_el) {
$(this).click();
}
});
});
});

Categories

Resources