JQuery - .click triggering when clicked anywhere should: upon clicking on a link - javascript

https://dl.dropboxusercontent.com/u/63617776/Capture.PNG
So as on the image, when you click on the map, a div is changed. Now when I click on a link in the div, I want the google maps div to change to another map.
But, the code I wrote either doesn't trigger at all or it triggers when I click anywhere on the page.
$('#nowydwor').ready(function(){
$(this).click(function(){
alert('foo');
});
});
Ofcourse the link looks like this:
{a id="nowydwor"} text {/a} (for some reason i couldn't enter < so I replaced it with {)
This triggers when user clicks anywhere on the page, for some reason. Also this is only a testcode for now, it is meant to display the alert. :) Any ideas?
EDIT: The link is contained in .html(), in a switch() statement.
case '#mazowieckie':
$('#info').html("CONTENT </h5><hr><strong><a id='nowydwor'>Skład Nowy Dwór Mazowiecki</a></strong> CONTENT");
break;

Calling ready only makes sense if you call it on the document/window to get notified as soon as the DOM is ready.
Try to bind the click handler on your DOM element directly:
$('#nowydwor').on('click', function(){
alert('foo');
});

I think what you were trying to do, is assign the click handler after the content of #info has changed. Unfortunately .ready() is only an event handler for the document ready event. It only fires once. Also changing the html of '#info' isn't triggering any events (IMHO).
You can work around this, using the .on-method on a parent element. Consider this html structure:
<div id="info">
<!-- This content is dynamically loaded -->
<a id="nowydwor">Click this to change map</a>
<!-- End of dynamic content -->
</div>
This makes it possible to call:
$('#info').on('click', '#nowydwor', function(){ /* Change map here... */ })
This assigns the event handler to #info, which is only called if the clicked element matches '#nowydwor'. Since '#info' is never removed, only the content changes, you don't have to apply it again.
The only point is, you have to determine what the id of the map/place is, because the event handler will be the same for all links.

Related

jQuery link instead of button trigger

So, i have this code snippet that opens a modal:
<button id="trigger-overlay" class="order">Open Overlay</button>
Now, i wanted to include it in Wordpress menu, but i cant add button tag there, so i added:
Open Overlay
And i am using jquery to add a ID to that link, like this:
$('.order').attr('id','trigger-overlay');
ID is added, but link doesnt open anything, aka, it links to "#" instead of opening a modal...
How could i fix this to make it work?
Thanks!
This thing may causing due to events binging order. So, your code $('.order').attr('id','trigger-overlay'); is executing right after click's binding event (I think that event looks like this one: $('#trigger-overlay').click(function() { ... });.
If you have ability to change that binding, please use jquery.on method: http://api.jquery.com/on/
So that code will looks like: $(document).on('click', '#trigger-overlay', function() { ... });.
Also you can just move $('.order').attr('id','trigger-overlay'); above the script with that event binding.
Based on your
<button id="trigger-overlay" class="order>Open Overlay</button>
I'm not sure how you got a modal to trigger, since it is not connected to an event handler like:
<button onclick="turnOverlayOn()">Demo Button</button>
In this case, there would be a function that targets the overlay/modal and turns its CSS display property from none to block or inline-block (however you would like to display it):
var turnOverlayOn = function () {
$('targetOverlayId').css('display','block')
}
I suggest focusing on attaching an onClick event that triggers a function that does what you want to make the overlay appear.
The function used to turn the overlay off could be:
var turnOverlayOff = function () {
$('targetOverlayId').css('display','none')
}
You could attach this to a different anchor tag or button to turn the overlay off.
Note: the event should work the same for an anchor tag as it does for a button.
In my understanding you want to trigger the button click event. Using the a tag with class order.
try
jQuery(document).on('click','.order',function(){
jQuery('#trigger-overlay').click();
});
You can trigger the click event using jquery. Since I have no knowledge of your DOM structure jQuery(document).on('click','.order',function().. will work even if your elements are dynamic (added to the DOM after the script execution) because the click event is bind to the document.
NOTE:
When using wordpress always use jQuery instead of $ to avoid conflicts.

jQuery Click Event Triggering On Multiple Elements (I only want 1)

When my overlay comes up, everything works well, but I added some code to close out the overlay, but this code gets triggered even when I'm just clicking my arrows. The following is the code that's being triggered, which is fine when I'm not clicking the arrows to change the image. But when I click the arrows, the background which is the overlay is also being trigger, so the image is changing but the overlay is also hiding.
$('#overlay').click(function() {
$(this).fadeOut('slow');
});
How can I be able to use the arrows without it also clicking on the background overlay? If you open up the project, you will see what I'm saying.
To open the project:
https://htmlpreview.github.io/?https://github.com/rodriguesandrewb/photo_gallery_v1/blob/master/index.html
To open the repository:
https://github.com/rodriguesandrewb/photo_gallery_v1
You want to use event.stopPropagation(): https://api.jquery.com/event.stoppropagation/
This prevents the event from bubbling (being triggered by other elements)
Your outter most element is #overlay. It means that no matter where you click you'll be always clicking on your #overlay element. That is way your callback is being always triggered and closing your image.
To fix your problem and make your image close only when clicking on it you could use:
$('#changeImage').click(function() {
$(this).closest('#overlay').fadeOut('slow');
});
Ok, there's a ton of code to sort out, so I'm guessing your overlay is
<div id="overlay" style="display: block;"></div>
and your event.target is deep down inside this:
<div class="mainCenter">
<div class="container">
<div id="topFixed">
<input type="text" id="search" placeholder="Search">
</div>
<ul id="gallery">
.......
I'm not 100% sure where your event.target is, (the element you want to click and not everything else). But it's safe to assume that after you click your intended button, the event continues to bubble up the event chain. The event chain is basically your event.target's ancestors which includes#overlay` which is at the very top of the event chain.
To prevent event bubbling (btw bubbling is the default behavior but in instances such as your's it's not desired.) try placing stopPropagation() after or inside at the end of your event handler.
I wish I could be more specific as to where and how to apply this code as it pertains to your source, but you didn't provide the specific areas that concern your eventListeners, eventHandlers, etc...
The #overlay is used in this example but I suggest you use the event.target parent instead. The purpose of this code is to accept an event like 'click' on an element (i.e. button) or multiple elements (i.e. buttons) through their mutually shared parent. That's one place to click for potentially several different buttons. At first you'd think that's non-sense and you'd say, "Sure that button is clicked because the parent was clicked, but now everything the parent is chained to will trigger everything else."
That would be correct except we have stopPropagation(); at the very end of your eventHandler. That will stop propagation of the event bubbling back up the event chain, so there's no more rogue triggers lighting up everywhere. Rogue Triggers® sounds like a great band name. :P
For details and a much better explanation: http://www.kirupa.com/html5/handling_events_for_many_elements.htm
var overlay = document.querySelector("#overlay");
theParent.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
alert("Hello " + clickedItem);
}
e.stopPropagation();
}

jQuery $(element) undefined whilst executing .click() method - returns element at all other times

Have a really strange issue that a colleague was facing which I managed to work around, but for the life of me cannot understand why his initial code did not work! - we have a legacy asp.net web application that is using MasterPages/Content controls and has jQuery mixed all over the web application providing some client interactivity.
Essentially there is a web form view that has a div containing a button which is initially hidden (display: none), upon clicking another menu item, this div is shown using jQuery BLOCKUI Plugin, blocking the rest of the UI and rendering the popup div into place - the user can then click the button, clicking the button should hide the containing div, and show another div that contains another two buttons - all should be simple.... but this is where it got funky:
Bear in mind none of this content is dynamically generated, all HTML elements are present within the .aspx view up front after the page is finished loading.
var blockUiRenderFrame = function (html, width, height) {
window.parent.$.blockUI({
message: html,
css: {
top: ($(window.parent).height() - height) / 2 + 'px',
left: ($(window.parent).width() - width) / 2 + 'px',
width: width
}
});
};
<div id="anotherContentFrame">
<p>some text</p>
</div>
<div id="contentFrame" style="display:none;">
<div id="myButtonContainingDiv">
<button id="aButton" />
</div>
<div id="myOtherButtonsContainingDiv"></div>
</div>
$(document).ready(function() {
$("#myButton").click(function() {
$("#myButtonContainingDiv").hide();
$("#myOtherButtonsContainingDiv").show();
});
});
<!-- A Button on the page calls this code -->
blockUiRenderFrame($("#contentFrame"), 200, 200);
What I observed occurring was what appears to be a complete loss of context, or executing the event under a different context all together... during the handling of the click event, the div elements, or indeed anything within the HTML div contentFrame all return undefined.
At any other time if I use the console/debugger, I can successfully return an element using say $("#myButtonContainingDiv").
The click event has its correct event element, I can use $(this) to get the button I clicked on, but even trying to select $("#myButton") within the actual click event handler code itself returns 'undefined'.
I can access $("anotherContentFrame") perfectly fine, at any time, including during the handling of the click event of #myButton.
The workaround I had to use in order to get this code to work was:
During the click event handler, use the following:
$(this).closest('div').hide()
$(this).closest('div').next().show()
As this was the only way I could get any reference to the DOM elements on the page to successfully hide/show them.
I can try to give out some more information if anyone wishes, I am not sure if anyone has ever seen an issue like this.
Thanks in advance!
Where's the code showing your button?
When you call $(element).click() it will try to bind to your element on the DOM that is already loaded (no async elements!). If you're loading the #myButton via a async call, you need to bind the click on a parent element and then filter the function call to your #myButton like this:
$(document).on('click', '#myButton', function(){});
This way you're sure that the element (in this case, document) existing when jQuery tries to bind the click event and it will only fire it when clicking on the filter you specified as the 2nd parameter to the .on() call, in this case, your #myButton element
Your event is not firing because jQuery doesn't know the element, because its state changed dynamically. In order to be sure to fire your click event, no matter the context, you can use
$(document).on('click', '#myElement', function(){});
By doing that, you are refering to the easiest "non dynamically generated" element, and jQuery will always be able to find your element.
You can then access your element properties with :
$(this)

JavaScript Click event fires via the Enter Key but not via the Mouse

Some code that looks like the following is firing the click event via the Enter key, but is not responding to the mouse click.
//a is an anchor element
a.addEventListener('click', function (e)
{
//Do Stuff...
});
This page demonstrates the problem. The relevant bit of code is at line 176. This is in the middle of development and currently only (sort of) works in Chrome.
Also, I just verified that it works if I use mousedown, so it's not just the case of an invisible element sitting in front of the anchor.
Any ideas?
Edit: Now that you've shown us the actual code you're using, the problem is related to the fact that the autoSuggest() function has it's own click handler and in that click handler, it is clearing the container which removes all <a> elements in the container so your link object gets destroyed (probably before your click event gets to process). So, you can get events that happen before the click (like mousedown), but after a click, the element is removed from the DOM.
If you tell us what you're trying to actually do when an auto-suggest item is clicked that is different than the default behavior of the autoSuggest() function and you point to any documentation for that function, then perhaps we could offer a better way to solve your issue.
The link may be firing and taking you off to a new page (or reloading the current page), thus preventing you from seeing the click code run. Usually when you process a click event on a link element, you need to prevent the default behavior:
//a is an anchor element
a.addEventListener('click', function (e) {
e.preventDefault();
//Do Stuff...
});
Another possibility is that you are trying to install the event handler too soon either before the DOM has been loaded or before this particular link has been created and thus no actual click event handler is attached to the DOM object. You can verify whether the event handler is even getting called by temporarily putting an alert("Click handler called"); in the event handler and see if that pops up or not.

Jquery class removed after link click, but second click is still recognized

I'm having a little problem. I'm trying to use Jquery load() function to load in stuff on a page using AJAX. After the content has been loaded, and the link gets tapped on a second time, I need to loaded content to slideup/hide; And when the same link is clicked for the 3+ time, I need to just toggle the loaded content display, since it's already been loaded once.
My problem is that after clicking the link once, I remove the loadable class, but on the second click the same function executes as if the class were still there. Here is my HTML:
<a title="Food" id="food" class="loadable" href="get-taste/food">Food</a>
<div class="food_load_space"></div>
The link triggers the load and the data loads into .food_load_space. And here's my JS:
$(document).ready(function(){
$('a.loadable').click(function(){ //executed upon link click 1;
url = $(this).attr('href');
linkid = $(this).attr('id');
toload = url + ' #content-area';
//now, remove loadable, add loaded and expanded
$(this).removeClass('loadable');
alert(toload);
$('.' + linkid + '_load_space').load(toload);
return false;
}); //kill loadable
I'm also planning on adding an .expanded class and a .loaded class so that the script knows at which state the link is in. But what happens is this function fires even if the .loadable class is gone.
The event has already been bound to the element, you need to manually unbind the event from the element(s) in question. This can be done by calling $(this).unbind('click');.
You may also wish to check if the element has the class in the event function.
The handler is bound the the element, not the selector.
If you only want it to exist for one click, use the one()(docs) method to bind it.
$('a.loadable').one('click', function(){
// and so on...
It will be automatically unbound after the first click.
The reason your second click is recognized is because jQuery has already binded an action to your element. You can't unbind the event just by removing the class. The class was only there to help you select that element (and style your element).
To remove the event binding, in your click function, you should do something like:
$('a.loadable').click(function() {
...your other code...
$(this).unbind('click');
});

Categories

Resources