jQuery .click() doesn't fire but console.log shows output - javascript

I'm having a problem in my code where I click a DOM-element using JavaScript. The click does not work and I am almost sure it is no dumb programming mistake (always dangerous to say).
After deleting some DOM-elements I want my code to click an element and trigger its onclick event. However this doesn't work. According to my code the event triggers but the event doesn't happen and the click event returns the jQuery object.
HTML:
<div class="castor-tabs">
<div class="castor-tab" data-path="../SiteBuilding/alertbox.js" data-saved="saved" data-editor="5475c897f1900editor">
<span class="castor-filename">alertbox.js</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab" data-path="../SiteBuilding/index.php" data-saved="saved" data-editor="5475c89903e70editor">
<span class="castor-filename">index.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab active" data-path="../SiteBuilding/makesite.php" data-saved="saved" data-editor="5475c8997ac77editor">
<span class="castor-filename">makesite.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
</div>
JavaScript:
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
});
The onclick event:
$(".castor-tabs").on("click", ".castor-tab", function() {
$(".castor-tab.active").removeClass("active");
$(this).addClass("active");
var editor = $(this).attr("data-editor");
$(".CodeMirror").hide();
$("#" + editor).show();
});
I saved the element in the window object for a reason. After the code runs and it skips the click-part I still have the DOM-element i want to click saved in the window object. This means I can run
console.log(window.newTab.click());
again. Surprisingly this does click the element and this does activate the click-event. It also returns the DOM-element instead of the jQuery-object.
The image shows in the first two lines the failed click. The third line is my manual input and the fourth line is the successful return value of the click().
I hope you can help me to solve this.
UPDATE
.trigger("click") unfortunately gives the same output..
UPDATE 2
To help you i made the website available on a subdomain. I know many of you hate it if you have to go to a different page but I hope you'll forgive me because in my opinion this cant be solved through JSFiddle.
The link is http://castor.marknijboer.nl.
After clicking some pages to open try closing them and you'll see what i mean.

try adding return false; at the end, when binding .castor-close click event
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
return false;
});

Instead of simulating a click, why not just pull the click logic out of your click function and just call the javascript function using the arguments that you'll need to perform your business logic?

Your code is working but not able to trigger click event binded to castor-close because i tag is empty. Put some text in it and check
<span class="castor-close"><i class="fa fa-fw fa-times">Click me</i></span>
DEMO

Your click handler has the requirement that the click target should have the class castor-close but when you are calling click via JavaScript you are clicking the parent element instead (.castor-tab), and the click handler doesn't react.

Related

Click event undo

I'm working on my very first site and have a problem with click event.
here is my website (it's unfinished): https://pawcio93.github.io/PortfolioSinglePage/
The problem is that #cancel does not work (function run after click, I checked it with alert, but click event does not undo itself at all. I also try to use .on .off method but with same result. If it's making something wrong or I can't use those methods to undo this 'click' function properly? If not, how should I perform that? Thank in advance for reply I will try to figure it out myself, waiting for Yours propositions
var chooseHobby = function() {
$(this).addClass('hobbyOnClick').removeClass('hobby firstInLine hobbyImg');
$('.hobbyImg').hide();
$('.hobby').css('display', 'none');
updateHeight2();
var id = this.id;
if (id == 'sport') {
if (document.getElementById("gym")) {
return;
} else {
$('#sport').append('<img id="runmaggedon" src="img/runmaggedon.jpg" alt="runmaggedon" />');
$('#sport').append('<img id="gym" src="img/gym.jpg" alt="gym" />');
$('#sport').append('<div class="sportText">\n\
<p>Runmaggedon is my hobby for over a year, it is challenging, hard and the people and athmosphere there is just great. For now my best distance is 24 km in mountain terrain, but it was not my last word! </p>\n\
\n\
</div>');
$('#sport').append('<div class="sportText"><p>Working out is something that I&#39m doing since studies. It is became the part of my daily routine, I love to work with my body and see physical ad power progress. Gym also help with self-discipline and well-being </p></div>');
$('#sport').append('<div id="cancel"><p>CANCEL</p></div>');
}
} else if (id == 'travel') {
alert("travel");
} else if (id == 'objectivism') {
alert("objectivism");
} else if (id == 'engineering') {
alert("engineering");
} else if (id == 'programming') {
alert("programming");
} else if (id == 'economy') {
alert("economy");
}
$("#cancel").bind("click", function() {
alert("function start");
$(".hobby").unbind("click", chooseHobby);
});
};
$(document).ready(function() {
$(".hobby").bind('click', chooseHobby);
});
A click is an event. It happens milliseconds (quite instantly) after a user click.
You can't "undo" it.
To that event, you can register a function to execute. Now to "undo" the changes made by such a function, you have to store the previous relevant states/values. And using another click event, you can give the impression of an undo.
Here is a really simple example which only changes a <h1> text.
// Store initial text.
var previousH1state = $("h1").text();
// Modify
$("#modify").on("click",function(){
$("h1").text("I'm modified!");
});
// Undo
$("#undo").on("click",function(){
$("h1").text(previousH1state); // Notice the stored text is used here.
});
// De-register functions tied to click events from the modify/Undo buttons.
$("#off").on("click",function(){
$("#modify, #undo").off("click");
console.log("Modify and Undo buttons are not working anymore");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>I'm unchanged.</h1>
<button id="modify">Modify the header above</button>
<button id="undo">Undo the modification</button><br>
<br>
<button id="off">Use .off()</button>
.off() is used to de-register a function from the event on an element. That is something else...
More on events.

Prevent anchor click after one click

I am facing one issue, I want to disable anchor click after one click. I have
on-click attribute set in my anchor tag. Below is my HTML
<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>
After I click "Verify" I am changing anchors text to "Verifying..." and one more thing I am trying to disable this anchor to avoid click in between the verification logic going on.
I have tried event.preventdefault() and also added disabled attribute to anchor.
But nothing works.
Please help!
If you were using jQuery for this you could have done this more easly.
Here we add a new class to a link to show that it has been clicked already. We check this when a click is made.
<a style="cursor:pointer;" id="someId">Verify</a>
$('#someId').on('click',function(){
//Check if button has class 'disabled' and then do your function.
if(! $(this).hasClass('disabled')){
$(this).addClass('disabled');
Myfuntion();
$(this).removeClass('disabled');
}
});
Here is a demo as to how it could be done using Javascript.
//Pass the event target to the function
function Myfuntion(elem) {
//If the element has no "data-status" attribute
if (!elem.getAttribute("data-status")) {
//Set attribute "data-status=progress"
elem.setAttribute("data-status", "progress");
//Change the text of the element
elem.textContent = "Verifying...";
//The setTimeout(s) below is only for the demp purpose
//Lets say, your verification process takes 4 seconds
//When complte
setTimeout(function() {
//Remove the attribute "data-status"
elem.removeAttribute("data-status");
//Notify the use that verification is done
elem.textContent = "Verified";
//Again, this is only for demo purpose
setTimeout(function() {
//User may verify again
elem.textContent = "Verify";
}, 1000);
}, 4000);
}
return false;
}
Link to the demo
There are plenty of ways to do this; one simple approach is to just redefine the function itself:
var myFunction = function() {
alert('clicked');
// do whatever your function needs to do on first click, then:
myFunction = function() { // redefine it
// to no-op, or to another action
alert('second click');
}
}
<a onclick="myFunction()">click me</a>

X-Editable: stop propagation on "click to edit"

I have an editable element inside a div which itself is clickable. Whenever I click the x-editable anchor element, the click bubbles up the DOM and triggers a click on the parent div. How can I prevent that? I know it's possible to stop this with jQuery's stopPropagation() but where would I call this method?
Here's the JSFiddle with the problem: http://jsfiddle.net/4RZvV/ . To replicate click on the editable values and you'll see that the containing div will catch a click event. This also happens when I click anywhere on the x-editable popup and I'd like to prevent that as well.
EDIT after lightswitch05 answer
I have multiple dynamic DIVs which should be selectable so I couldn't use a global variable. I added an attribute to the .editable-click anchors which get's changed instead.
editable-active is used to know if the popup is open or not
editable-activateable is used instead to know if that .editable-click anchor should be treated like it is
$(document).on('shown', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).attr("editable-active", true);
});
$(document).on('hidden', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).removeAttr("editable-active");
});
The check is pretty much like you've described it
$(document).on("click", ".version", function() {
$this = $(this)
// Check that the xeditable popup is not open
if($this.find("a[editable-active]").length === 0) { // means that editable popup is not open so we can do the stuff
// ... do stuff ...
}
})
For the click on the links, simply catch the click event and stop it:
$("a.editable-click").click(function(e){
e.stopPropagation();
});
The clicks within X-editable are a bit trickier. One way is to save a flag on weather the X-editable window is open or not, and only take action if X-editable is closed
var editableActive = false;
$("a.editable-click").on('shown', function(e, reason) {
editableActive = true;
});
$("a.editable-click").on('hidden', function(e, reason) {
editableActive = false;
});
$("div.version").click(function(e) {
var $this;
$this = $(this);
if(editableActive === false){
if ($this.hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
}
});
Fixed Fiddle
It's not pretty, but we solved this problem with something like:
$('.some-class').click(function(event) {
if(event.target.tagName === "A" || event.target.tagName === "INPUT" || event.target.tagName === "BUTTON"){
return;
}
We're still looking for a solution that doesn't require a specific list of tagNames that are okay to click on.

Hiding Bootstrap Popover on Click Outside Popover

I'm trying to hide the Bootstrap Popover when the user clicks anywhere outside the popover. (I'm really not sure why the creators of Bootstrap decided not to provide this functionality.)
I found the following code on the web but I really don't understand it.
// Hide popover on click anywhere on the document except itself
$(document).click(function(e) {
// Check for click on the popup itself
$('.popover').click(function() {
return false; // Do nothing
});
// Clicking on document other than popup then hide the popup
$('.pop').popover('hide');
});
The main thing I find confusing is the line $('.popover').click(function() { return false; });. Doesn't this line add an event handler for the click event? How does that prevent the call to popover('hide') that follows from hiding the popover?
And has anyone seen a better technique?
Note: I know variations of this question has been asked here before, but the answers to those questions involve code more complex than the code above. So my question is really about the code above
I made http://jsfiddle.net/BcczZ/2/, which hopefully answers your question
Example HTML
<div class="well>
<a class="btn" data-toggle="popover" data-content="content.">Popover</a>
<a class="btn btn-danger bad">Bad button</a>
</div>
JS
var $popover = $('[data-toggle=popover]').popover();
//first event handler for bad button
$('.bad').click(function () {
alert("clicked");
});
$(document).on("click", function (e) {
var $target = $(e.target),
var isPopover = $target.is('[data-toggle=popover]'),
inPopover = $target.closest('.popover').length > 0
//Does nothing, only prints on console and wastes memory. BAD CODE, REMOVE IT
$('.bad').click(function () {
console.log('clicked');
return false;
});
//hide only if clicked on button or inside popover
if (!isPopover && !inPopover) $popover.popover('hide');
});
As I mentioned in my comment, event handlers don't get overwritten, they just stack. Since there is already an event handler on the .bad button, it will be fired, along with any other event handler
Open your console in the jsfiddle, press 5 times somewhere on the page (not the popover button) and then click bad button you should see clicked printed the same amount of times you pressed
Hope it helps
P.S:
If you think about it, you already saw this happening, especially in jQuery.
Think of all the $(document).ready(...) that exist in a page using multiple jquery plugins. That line just registers an event handler on the document's ready event
I just did a more event based solution.
var $toggle = $('.your-popover-button');
$toggle.popover();
var hidePopover = function() {
$toggle.popover('hide');
};
$toggle.on('shown', function () {
var $popover = $toggle.next();
$popover.on('mousedown', function(e) {
e.stopPropagation();
});
$toggle.on('mousedown', function(e) {
e.stopPropagation();
});
$(document).on('mousedown',hidePopover);
});
$toggle.on('hidden', function () {
$(document).off('mousedown', hidePopover);
});
short answer
insert this to bootstrap min.js
when popout onblur will hide popover
when popout more than one, older popover will be hide
$count=0;$(document).click(function(evt){if($count==0){$count++;}else{$('[data-toggle="popover"]').popover('hide');$count=0;}});$('[data-toggle="popover"]').popover();$('[data-toggle="popover"]').on('click', function(e){$('[data-toggle="popover"]').not(this).popover('hide');$count=0;});
None of the above solutions worked 100% for me because I had to click twice on another, or the same, popover to open it again. I have written the solution from scratch to be simple and effective.
$('[data-toggle="popover"]').popover({
html:true,
trigger: "manual",
animation: false
});
$(document).on('click','body',function(e){
$('[data-toggle="popover"]').each(function () {
$(this).popover('hide');
});
if (e.target.hasAttribute('data-toggle') && e.target.getAttribute('data-toggle') === 'popover') {
e.preventDefault();
$(e.target).popover('show');
}
else if (e.target.parentElement.hasAttribute('data-toggle') && e.target.parentElement.getAttribute('data-toggle') === 'popover') {
e.preventDefault();
$(e.target.parentElement).popover('show');
}
});
My solution, works 100%, for Bootstrap v3
$('html').on('click', function(e) {
if(typeof $(e.target).data('original-title') !== 'undefined'){
$('[data-original-title]').not(e.target).popover('hide');
}
if($(e.target).parents().is('[data-original-title]')){
$('[data-original-title]').not($(e.target).closest('[data-original-title]')).popover('hide');
}
if (typeof $(e.target).data('original-title') == 'undefined' &&
!$(e.target).parents().is('.popover.in') && !$(e.target).parents().is('[data-original-title]')) {
$('[data-original-title]').popover('hide');
}
});

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Categories

Resources