jquery code not executing from script, but executing from dev panel - javascript

http://www.henrybuilt.com/trade2/resource.php?id=100
Check out the link above. Login: asdf, asdf
EDIT: Click on bamboo on the link above once you've logged in. Thanks.
The following code (which toggles a 'popup' window (div)) won't execute on the page, but will work when copied and pasted in the dev panel.
$(".maintypedata img").click(function() {
console.log("test");
if(open == false) {
var src = $(this).attr("src");
$(".popup").html("<img src='"+src+"'/>");
open = true;
$(this).addClass("selected");
$(".popup").slideFadeToggle(function() {
});
}
});
How can I make it run from the script?

The click handler you've shown is bound to any ".maintypedata img" elements that exist when that code runs. But, the img elements in question are appended to the document dynamically after the "Bamboo" option is clicked. So you need to either run that .click() code after the elements are appended (which is what you were doing by running it from the console) or change it to work as a delegated event handler:
$(".maintypedata").on("click", "img", function() {
console.log("test");
if(open == false) {
var src = $(this).attr("src");
$(".popup").html("<img src='"+src+"'/>");
open = true;
$(this).addClass("selected");
$(".popup").slideFadeToggle(function() {
});
}
});
That is, bind the click handler to an element that exists initially, in this case ".maintypedata", but specify a selector in the second parameter to .on() and jQuery will only run your handler if the clicked item matches that second select at the time of the event.
(A delegated handler is also more efficient than binding the same handler to lots of separate elements, but that's just an added bonus.)

Related

onClick function used on dynamic content not working properly

I hit a problem with the onclick function when i add divs with ids like "n_block"+(1-~). When I use the jquery zoom function on the objects to make them smaller or bigger onClick doesn't work anymore. I'm not really good at programming so the code might be kind of confusing.
Heres the code i use for the onClick of items:
$(document).on("click",function (e, ui){
//When the document gets clicked, check if one of the items was clicked.
if($(e.target).is($("#n_block" + cloneCount1)) || $(e.target).is($("#n_block" + cloneCount1+ " span"))){
//Set current item.
var item = $("#n_block" + cloneCount1);
//Set style to current item.
item.css("border-color", "Black");
item.css("border-width","2px");
item.css("background-color", "floralwhite");
jsPlumb.repaintEverything();
//Check if key Delete was pressed while item selected & delete that item with his children.
$('html').keydown(function(e){
if(item.css("border-width")=="2px"){
if(e.keyCode == 46) {
/* Prevents line bugging*/
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
var razred = getClass(item, "b_"),
id = item.prop("id");
item.remove();
if(razred == "b_2"){
$(".ovoj."+id).remove();
}
else if (razred == "b_4"){
$(".ovojLoop."+id).remove();
$(".empty_block_c."+id).remove();
}
if ( $('.objects').find('div').length == 2) {
$(".objects").empty();
$(".objects").append('<div class="b_s" id="start_block">START</div><p id="start_text">Insert symbols here!</p><div class="b_s" id="end_block">STOP</div> ');
}else{
/* Connects objects together with line. ****/
povezi(cloneCount, tip_crte, ".objects");
}
}
jsPlumb.repaintEverything();
}
});
}
// If item is not clicked set this css to the current item.
else{
$("#n_block" + cloneCount1).css("border-width","1px");
jsPlumb.repaintEverything();
}
});
And heres the zoom code for zooming in when button is clicked:
var currentZoom = 1.0;
$(".zoomin").click(function (){
//Detaches the connections from item to item.
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
//Prevents spamming of button, animates the objects
$(".project").stop().animate({ "zoom": currentZoom += .1}, "slow", function() {
if(!$(".objects").children().is($("p"))){
povezi(cloneCount, tip_crte, ".objects");
}
});
});
Use event delegation for binding events to dynamically added elements.
$(document).on('click', ".zoomin", function (){
//Your code.
});
When you use normal .click() to bind event to an element, then that even gets bound to only those elements which exist in the DOM at the moment of the execution of code. Using event delegation, you can tell jQuery that we need to add the handler to every '.zoomin' element which comes inside a particular element no matter when it is added.
The solution depends when exactly is the script which tries to bind the events are executed.
For Eg: Lets assume this script is in document ready function of jquery
$(document).ready(function(){
$(".zoomin").click(function (){
//your logic here
});
});
Here this script is executed when the page HTML is completed loading into the browser. Now when the script executes it tries to find a element with the class zoomin and if found it will add a event to that element and move on. If the element is not found the script just moves on. So we should actually take care of when the script is executed and is the intended element available at that particular instant of time. If the element is not yet available in the HTML (element might come in later dynamically using jquery) we have 2 options to bind event to the element.
1) Execute the script when the element is being added into the HTML: Lets say I have a event which brings up a pop up with some image. Now I want to zoomin and zoomout the image. Since the image in the popup is added dynamically and I have control of when its being added, I can do this.
$(document).ready(function(){
$('.ViewImage').on('click',function(){
// some code is executed which brings up the popup
// now we know that the image is added into html we can now run the script
$(".zoomin").click(function (){
//your logic here
});
});
});
2) We have no Clue/ Control when the element is added into HTML but still want to bind a event to it: This is scenario where we have no control on when the element is being added or not sure where it is being added from (might be from some external plugin used etc) or not having control at all on the element which is added. Thats when we use this syntax as suggested by #Rejith R Krishnan
$(document).on('click', ".zoomin", function (){
//Your code.
});
This will work on all the elements which are in the HTML at the time of execution of the script and on the elements which will be added in the future with the class name zoomin. So this script can be placed inside/ outside of jquery document ready event

Running Master page scripts on imported page lines

I'm importing some php into a div block using a link like this
<a class="ajax-link" href="login.php">Login/Register</a>
and such script (that uses jquery load to fill the div block).
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});
});
Now let's say the loaded php file after running the php portion also contains a link with "ajax-link" class and I want that link too to change the contents of that div block
<?php
...
?>
<a class="ajax-link" href="view.php">View content</a>
But rather than running the above mentioned function on it, it seems to ignore it completely and opens a new page instead.
So basically... how can I run that script on imported parts of the page?
This is where event delegation comes in handy.
$(document.body).on("click", "a.ajax-link", function(e) {
// ...
});
This code needs to be re-run ... dynamically added objects are not included in previous on clicks.
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});
... you could also ... turn off the old watcher.
$("a.ajax-link").off("click");
UPDATE:
Try ...
$("a.ajax-link")
.off("click")
.on("click", function(e) {
e.preventDefault();
$("#body-element").load(this.href);
});
You have to apply the click listener on the newly added link as well, as the element has to be loaded into the DOM when applying the click listener in order for it to be applied. However, if you just re-run the same code you'll like run into the problem of having two event listeners on the first ajax-link.
Try this:
// We still use on doc ready to be sure the
// first link is present before applying listener
$(function()
{
// Reset all listeners on ajax-links and
// then apply listeners via function
resetAjaxLinks();
});
// This function will remove any ajaxlink
// listeners and then apply them correctly
function resetAjaxLinks()
{
// Remove event listeners and then on click....
$("a.ajax-link").off('click').on("click", function(e)
{
// Prevent default link action...
e.preventDefault();
// Load in your content...
$("#body-element").load(this.href);
// Once content is loaded in, reset event listeners!
resetAjaxLinks();
});
}
EDIT: This is not the best method for this. Instead, use event delegation as specified by this answer.

How to catch all the links, read their attributes and prevent them from executing?

I want to catch all the .click() events that occurs on links on my page. Also, I want to read attributes of a link currently clicked. As far I have this, but there is a problem with it:
$("a").click(function (e) {
e.preventDefault();
$("#myPage").load("/ #myPage");
});
First of all, this code works only one out of two times - first time I click on a link, this code doesn't work, second click, this code works, third click, doesn't, etc. Why is that? Also, how can I read attributes of a link? I need to read src and class attributes.
Edit: What I need to do, is to catch whenever someone clicks on a link, stop that from happening, read href and class attributes of a link, and then proceed with loading the page (but not reloading, just replacing #myPage)
Edit2: Okay, so now the only problem is, why is it working one out of two times for me? When I load the page, then click a link, jquery works fine, but after second click, it is not hitting my $("a").click() event!
Solution: I fixed my problem by replacing .click() with .live() - now works every time. ;)
first part: How can I prevent link click:
just return false from your click event
$("a").click(function(e) { return false; });
Second part: how can I read attribute of a link
$("a").click(function(){
var href= $(this).attr('href');
alert(href);
return false;
});
see this fiddle
$("a").on('click', function(e) {
// stop click event
e.preventDefault();
// get href attribute of currently clicked item
var hrefAttr = $(this).attr('href');
// get class attribute
var classAttr = $(this).attr('class');
// do loading here
});
According to http://api.jquery.com/click/ the click() handler is potentially fired twice. Once for mousedown and once for mouseup. Perhaps you can utilize $.on('mouseup', function(e) { }); instead?
For attributes you can use:
$('a').attr('src');
In summary:
$("a").on('mouseup', function (e) {
e.preventDefault();
var src = $(this).attr('src');
$("#myPage").load("/#myPage");
});

jQuery click anywhere in the page except on 1 div

How can I trigger a function when I click anywhere on my page except on one div (id=menu_content) ?
You can apply click on body of document and cancel click processing if the click event is generated by div with id menu_content, This will bind event to single element and saving binding of click with every element except menu_content
$('body').click(function(evt){
if(evt.target.id == "menu_content")
return;
//For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
if($(evt.target).closest('#menu_content').length)
return;
//Do processing of click event here for every element except with id menu_content
});
See the documentation for jQuery Event Target. Using the target property of the event object, you can detect where the click originated within the #menu_content element and, if so, terminate the click handler early. You will have to use .closest() to handle cases where the click originated in a descendant of #menu_content.
$(document).click(function(e){
// Check if click was triggered on or within #menu_content
if( $(e.target).closest("#menu_content").length > 0 ) {
return false;
}
// Otherwise
// trigger your click function
});
try this
$('html').click(function() {
//your stuf
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
you can also use the outside events
I know that this question has been answered, And all the answers are nice.
But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.
In a more general way, we can do something like this:
$('body').click(function(evt){
if(!$(evt.target).is('#menu_content')) {
//event handling code
}
});
This way we can handle not only events fired by anything except element with id menu_content but also events that are fired by anything except any element that we can select using CSS selectors.
For instance in the following code snippet I am getting events fired by any element except all <li> elements which are descendants of div element with id myNavbar.
$('body').click(function(evt){
if(!$(evt.target).is('div#myNavbar li')) {
//event handling code
}
});
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
You could try this:
$(":not(#menu_content)").on("click", function(e) {
e.stopPropagation();
// Run your function when clicked anywhere except #menu_content
// Use with caution, 'cause it will prevent clicking on other elements
});
$("#menu_content").on("click", function(e) {
e.stopPropagation();
// Run when clicked on #menu_content
});

Click handler fired only once

I have a set of links that I iterate over and add click handlers. Each link when clicked, fires an ajax request which upon success creates a div containing response data, and appends it to the DOM. The newly appended div (a floating div similar to a small lightbox) however, is removed when the user clicks close(on the div) or clicks anywhere else on the screen. I have a simple script below to monitor this change, but the click handler fires only once and does not work until after a page refresh. What am I doing incorrectly?
var monitorChange = function () {
//Check if div has been appended to the dom and if so continue to monitor it
if ( $('div.justappended').length > 0 )
{
setTimeout(monitorChange,100);
}
else
{
//div has been removed from the dom
alert('div removed');
//...do additional stuff here
}
};
$( 'span.someElements' ).each( function () {
var that = $(this);
$(that).click( monitorChange );
});
From what I understand, you are looking to have your on click event still work with ajax generated code. You need to use the live command in this case. http://api.jquery.com/live/
$('span.someElements').live('click', monitorChange);

Categories

Resources