Strange behavior of jQuery code in the href attribute - javascript

I saw that it's possible place jquery code in the href attribute of the html a tag.
That code, however, works so I do not understand: it works after the second click.
Why?
JS
<br>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<a id="myId" href='javascript:
$(document).ready(function(){
$("#myId").click(function() {
alert("ok jQuery");
});
});'>jQ</a>

In the first click, the function in href attribute gets executed and the handler gets bound to the 'myId' anchor element. In the second click handler gets executed and it shows alert.

Nothing strange in this behavior.
There are no jQuery click handlers bound to your link at the beginning.
However, when you click it at the first time, it executes the following script from its href:
$(document).ready(function() {
$("#myId").click(function() {
alert("ok jQuery");
});
});
and binds a handler to your link.
So, after the first click you have no alert, but you now have a click handler bound to your #myId.
When you click it at the second time, it fires fresh-bound jQuery event, which shows the alert.
Also, it executes href again, so when you click this link again, you will get two (the same) click handlers and two alerts, and number of alerts will be incremented each time.

The first click defines the click event to show the alert box.
The second click executes the code and show the alert box.
As the comment, you shouldn't include this code into the href attribute since that's a bad practice.

Related

Assign event to button from external library

Every time I press a button, there is a random chance that a alertify alert window popups. The alertify alert popup is something I use instead of javascript Alert, just to get a nicer design.
Alertify library
And here is a screenshot of the current situation:
I want to assign a event to the OK button. When I use the "inspect element" function in google chrome, I see that this green OK button has an id called "alertify-ok", so I want to assign an event when this button is pressed.
I've tried to add this part to my HTML document in the script part:
$( "#alertify-ok" ).on( "click",function() {alert("finally");});
But nothing happens. The reason why I need this to work, is that the youtube popupmodal should come up right after I've pressed the OK button. I belive the error comes because the alertify window with HTML is from an external library, so how can i do this?
Alerts and the others take callback functions on creation, https://github.com/alertifyjs/alertify.js/blob/0.3.12/src/js/alertify.js#L608. You don't need to attach another event listener, just give it the function you want it to execute. example below:
alertify.alert("alerttext", function(e) {
functionIWantToCall();
});
You can put the event on an element you know is already existent (like "body") and specify it to trigger only when the wanted element is clicked:
$(" body").on({
click: function () {...
}
}, "#trigger");

calling js function works only for the first time on jquery mobile

on jquery mobile web app I'm calling js function on close button. That js function close it's callers div parent.
That works fine, but problem is that I have multiple close buttons and this function works perfectly first time,
after that onclick doesnt work. It doesnt enter into js function.
I tried to put js function at very bottom of my _Layout.cshtml page but it doesnt change anything.
update
<script type="text/javascript">
$('#closeTable').click(function () {
$(this).parent().hide();
});
</script>
<div id="closeTable"></div>
Your problem is originating from the fact that you're using an ID to add event listeners to. In your JS, you have this line:
$('#closeTable').click(function () { ...
This line attaches a click event handler to the div with ID closeTable. Since there can only be one element with this ID, once it's hidden the user can't click it again and so the function won't be executed again.
If you have multiple close buttons as you say, you should instead use a class selector to attach handlers:
$(".closeTable").click(function() { ...
This will instead attach a listener to every element with class closeTable. This means that when any of them are clicked the function will execute, so it will work multiple times.
Hope this helps.

Linking html element to jQuery.click() using attribute "title"

I have a html code:
<a title="intro">INTRO?</a>
I need to link a jQuery click event on the tag. Using the solution given here I wrote the following javascript:
jQuery("a[title='intro']").click(alert("abc"));
However the page is alerting ("abc") on page load rather than on clicking the tag. Also to inform that the above code is NOT inside the load function jQuery(function() {... } and is a separate function.
Any solutions pls?
You are invoking the alert function during the event registration and is passing the value returned by the alert as the click callback handler.
Instead you need to pass a function reference as the click callback and within the function you can add the alert call
jQuery("a[title='intro']").click(function(){
alert("a")
});

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

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.

jQuery / JavaScript Bubbling and stopPropagation doesn't work

I'm making an edit button which pops up a modal box with a form to edit it. jQuery then sends this form to my server and I get a JSON response back. However, due to my bubbling issue, if I click on, for example, all of the edit buttons and then click on the last one and change a field, it does it across all of them.
$('.edit').click(function(event){
//more code...
modal_submit(the_id);
event.stopPropagation();
});
and then the submit event:
function modal_submit(the_id){
$('#modal form').submit(function(){
//This will alert every time I have EVER clicked on an edit button
alert(the_id);
return false;
});
}
finally all of this is inside of a getScript:
$.getScript('js/edit.js',function(){
create_edit_btn();
});
I've only used this 1 other time, and it worked, but I also had to do this.event.stopPropagation, but if I do "this" now it says this.event is undefined, but like I said, this exact code worked before for another script I did.
Does anyone have any ideas? :\
EDIT:
the html is:
<li>
<input id="item1" type="checkbox" value="webhosting|15" title="Web Hosting">
<p>Hosting for your web site</p>
</li>
An event can have multiple event listeners. Each time you use $(element).submit(whateverFunction) you are adding another whateverFunction to the submit event. If you only want only the last listener to be the action that is taken upon envoking the event, try doing this:
function modal_submit(the_id){
$('#modal form').unbind(); // this will remove all other event listeners from this element
$('#modal form').submit(function(){
//This will alert every time I have EVER clicked on an edit button
alert(the_id);
return false;
});
I think you event.stoppropagation does its job already. It stopped all the bubbling on the click event of the button (ie, if you try checking the document body, it won't have mouse click event anymore). The reason why codes within submit of the form is still executed, is because this is called by the button's default action.
Together with event.stoppropagation(), I suggest you include this:
event.preventDefault();
So that the default action will not used and only the codes within your handler is executed.
Is this in the function that creates edit buttons?
$('.edit').click(function(event){
//more code...
modal_submit(the_id);
event.stopPropagation();
});
If it this, then it will add this handler multiple times to the same elements, causing a flurry of alerts. Use live, which will place the handler on every matched element, even if is is added later in execution.

Categories

Resources