Calling the inline JavaScript on a link using jQuery - javascript

I am modifying an ancient table which has inline JavaScript in the form of <a href="javascript:<lots of shit>">. The inline JavaScript works, but it would take months to rewrite it so that it fits my assignment, which is when an outer element is clicked the inline JavaScript should be executed.
I'm sorry if I'm not making any sense, but I have been as thoughtful as to provide a fiddle. (The table aspect shouldn't matter.) TL;DR: when I click one of the colored div's I would like its inner alert() to execute and how do I do that?
Edit. Also, the link is actually hidden!
Edit #2. And, as for now, none of the HTML should be tampered with. Only jQuery/JavaScript.
Edit #3. I've updated the script to work with my table. The inner <span> is now not needed, I can select the <a> directly. Now I would just like to know if I'm using stopPropagation() correctly?
Code:
$(function () {
$('table.result-v2 tr.view').bind('click', function () {
var $this = $(this),
$next = $this.next();
if ($next.attr('class') == 'detail') {
var $buttons = $this.find('td.buttons'),
$link = null;
if ($next.css('display') == 'none') {
$link = $buttons.find('a.show-link');
} else {
$link = $buttons.find('a.hide-link');
}
if ($link != null) {
eval($link.attr('href')); // evaluate found link
$link.bind('click', function (event) {
event.stopPropagation(); // is this needed when the link never can be clicked (it's hidden)?
});
}
}
});
});

Here is a quick hack that made your code work. And just to note that this is totally not how it should be done!
http://jsfiddle.net/2QaUX/1/
Instead of triggering a click, evaluate the inline script inside the href attribute:
Old:
$(function () {
$('.foo').bind('click', function () {
$(this).find('.bar').parent().trigger('click');
});
});​
New:
$(function () {
$('.foo').bind('click', function () {
eval($(this).find('.bar').parent().attr('href'));
});
$('.bar').parent().bind('click', function (event) {
event.stopPropagation();
});
});​

just place that js whithin a function
function clikEvent(ele)
{
//<lots of shit>
}
and call it on onclick and replace href js with void like
<a href="javascript:void(0)" onClick='clikEvent(this)'>
you have to also tack care of the data passed I have placed parameter ele wich will point the href so you can retrive id of or any other thing
if you want to use jQuery
$('#idofAtag').click(function(){//<lots of shit>});

There are two issues here. One is event propagation. When you click the div, you trigger a click on the link, which is also a click on the div. This creates an infinite loop which will quickly exceed the maximum call stack size. To get around this, you need to do two things:
Only execute the window.location.href assignment if the user clicked on the div and not the a within it.
If the user DOES click on the a, prevent the event from bubbling up to the div
The second issue is that the 'click' event on a link won't execute javascript stored in an href attribute. what you want to do is set window.location.href.
$('.foo').on('click', function (e) {
var link = $(this).find('.bar').parent('a');
if(e.target != link.get(0)) {
window.location.href = link.attr('href');
}
});
$('.foo').on('click', 'a', function(e) {
e.stopPropagation();
});
Here's a demo
--- jsFiddle DEMO ---
- NOTE - I would strongly recommend finding another way to handle this situation, but if you cannot alter the existing links, this option is viable.

Related

how to handle click event on dynamic content?

i have this HTML code on a page when my page loaded:
<div class="divmain">Add
<span class="spn">123</span>
</div>
when you click on that span it will create another span and show hi alert to you,
when the page loaded for the first time it works fine and write another span on that dive as the same the old span but after that if you click on the new span it works not.
i did some test and found if i add this code :
$('.spn').on("click", function (e) {
showalert(this);
});
on the "spanwriter" function it will works , i mean if that function be like this:
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
<------- this event must be add here until it --------------->
$('.spn').on("click", function (e) { works
showalert(this);
});
}
why i should add click event at the end of wrote content until span can get that event and works?
i used jquery-1.10.2.js on my sample
my all codes are:
$(function () {
$('.divmain').on("click", function (e) {
spanwriter(this);
});
$('.spn').on("click", function (e) {
showalert(this);
});
});
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
}
function showalert(master) {
alert("hi");
}
you have to do the same but with document.on("click")
$(document).on("click", ".buttonClass", function() { console.log("inside"); });
$('.divmain').on("click" make a kind of binding when document is loaded, so when you add dynamix elements to the dom it is noit catched. Whith the use od document.on, it works even if you add dynamic content to the document.
The simplest and best solution to your problem is to attach the event listener to a parent element in the dom and pass the second parameter of the on() method as described in the jQuery documentation (http://api.jquery.com/on/)
In other words you should have something along the lines of:
$('body').on("click", ".spn", function (e) {
showalert(this);
spanwriter(this);
});
and then have the spanwriter() add the new span to the parent of the element it's been called upon.
I hope this is what you were looking for and answers your question.

jQuery: Prevent click on sub-element's class: redirect page on tr click EXCEPT certain td

I've been searching for like 30 minutes already, so I apologize if I missed this answer already. I've seen a lot of CLOSE ones, but none quite like this.
I have an imported JavaScript function which is used in several files. It makes it so any table whose row has a clickable-row class will redirect to the href attribute, thereby making the whole row act like an anchor tag.
However, on some pages I'll have on td be populated with a checkbox, which I want to be able to click WITHOUT the page redirecting (so I can select multiple rows in the table).
Here is my current function:
jQuery(document).ready(function() {
jQuery('.clickable-row').click(function() {
window.document.location = jQuery(this).attr('href');
});
});
I want it to do something like the following, but this doesn't work:
jQuery(document).ready(function() {
jQuery('.clickable-row').click(function() {
if(!jQuery(this).closest('td').hasClass('skip-click')) {
window.document.location = jQuery(this).attr('href');
}
});
});
Any ideas on how to handle this?
You need to use e.target.
this inside the handler will refer to the .clickable-row element, not the element which actually triggered the click. The target property of the event object will return the element that triggered the event.
jQuery(document).ready(function ($) {
$('.clickable-row').click(function (e) {
if (!$(e.target).closest('td').hasClass('skip-click')) {
window.document.location = jQuery(this).attr('href');
}
});
});

Dynamically created "read more" link expands all the content instead of just one

What I was trying to code was the following:
Find every div of given class
If one of them happens to be higher than my maximum, make it 75px high and hide overflow, and add a "read more link" after this specific oversized element.
Make the link work...
I succeeded up to no. 2. However, the link on click expands all the content in all divs starting from the one it should expand downwards.
What am I doing wrong?
Thanks in advance!
$(function() {
$('.text').each(function() {
var content = $(this).find('.text_content');
if(content.outerHeight() >75) {
content.css('height','75px').css('overflow','hidden');
content.after('<div class="text_readmore">read more</div>');
$('.text_readmore').each(function() {
$(this).click(function() {
content.css('height','').css('overflow','');
});
});
}
});
});
You're using the content variable inside your .click handler, which isn't point to what you want. You can also refactor your code so that .click handler is defined once for all such text_readmore links, for efficiency.
Try something like this:
$(function() {
$('.text').each(function() {
var content = $(this).find('.text_content');
if(content.outerHeight() >75) {
content.css('height','75px').css('overflow','hidden');
content.after('<div class="text_readmore">read more</div>');
}
});
});
$(document).on('click', '.text_readmore', function() { // event delegation
$(this).closest('.text_content').css('height','').css('overflow','');
});
If you're using a version of jQuery before 1.7 (which is when .on was added), use .delegate instead:
$(document).delegate('.text_readmore', 'click', function() { // event delegation
$(this).closest('.text_content').css('height','').css('overflow','');
});

Jquery issue with variable

I have the following example: http://jsfiddle.net/gespinha/yTjUL/13/
The variable should be triggered on click, making the link change class from on to off and change colour from red to green. But instead it starts already green, thus making the function useless.
Why does it not work?
HTML
<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>
JQUERY
$(document).ready(function () {
var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});
});
You seem to be under the impression that the variable will store a chain of actions to perform later, when the variable is 'called,' but that's not (clearly) what happens: the first line, within the ready() handler, in the var assignment, finds the .on element and performs the actions you specify, storing the .on element(s) in the variable (as jQuery methods almost all return the this object).
Instead:
$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});
Or, more simply (if you want to toggle between 'states') use toggleClass() and $(this) (rather than selecting from the whole of the document each time the user clicks the given element):
$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});
Also, rather than using javascript:void(0) in the href, simply use jQuery to prevent the default action, with:
$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});
JS Fiddle demo.
References:
click().
event.preventDefault().
toggleClass().
It doesn't work that way, the variable will just contain the result of whatever methods you called, and for jQuery that means the element will be returned, so the variable $myVar only equals $(document) inside the event handler, it does not call the chained methods again.
You have to do:
$(document).ready(function () {
$('#link').on('click', function () {
$('.on').toggleClass('on off');
});
});
$(document).ready(function () {
$('#link').click(function () {
$(".on").addClass("off").removeClass("on");
});
});
As Guilherme Sehn noted, the $myVar variable is not needed. Just put your code in the click event. In addition, the link selector needs to be "#link", not "link".
By doing this, you'll be executing these actions and storing the return value (which will be the jQuery elements) inside $myVar. You can just put your code inside the click trigger function.
$('#link').click(function () {
$('.on').addClass('off').removeClass('on');
});
Also, you forgot the # before your ID. Without that your code will select link tags, not the element with the id link. And you do not need to explicity use $(document).find('.on') as all DOM elements are inside it.
I guess you meant $("#link")... and not $("link")
And if I understand right - the full script should be:
$(document).ready(function(){
$("#link").click(function(){
$(".on").addClass("off").removeClass("off");
});
});
You don't invoke the function and your selector is wrong.
$(document).ready(function () {
$('#link').click(function () {
$(document).find('.on').addClass('off').removeClass('on');
});
});

Javascript + jQuery, click handler returning false to stop browser from following link

I'm trying to stop the browser from following certain links, rather I want to unhide some Divs when they are clicked.
I'm having trouble just getting the links to not be followed though.
Here's what I have:
var titles = $('a.highlight');
jquery.each(titles, function(){
this.click(function(){
return false;
});
});
It seems like the click handler is not being assigned. What am I missing?
Try
this.click(function(e){ e.preventDefault(); }
Actually, it looks like you might need to use the jQuery constructor on this:
$(this).click(function(){ return false; }
You could also try using parameters on the each function instead of using this:
jQuery.each( titles, function(index, elem) { $(elem).click( function() { return false; } ) } );
Personally, I would just do titles.each( ... though. In that instance you can use this to bind the click handler. I am not sure off the top of my head what this binds to with jQuery.each
Or just calling click on titles:
titles.click( function() { return false; } )
That will bind click to every element in titles. You don't need to loop through them.
You can compress that jquery a bit:
$('a.highlight').click(function() { return false; });
You should also make sure that:
There are no other click handlers registered for those elements later on.
The code you have is attaching after the elements have loaded. If they're not completely loaded, they won't be found in the $('a.highlight') selector. The easiest way to do this is to put your code in a $(document).ready(function() { *** code here *** }); block.
Edit: As per other responses - the problem was that this represents a DOM object, while $(this) is a jquery object. To use the .click function to attach a handler, you need a jquery object.
In short, using this inside the each loop won't work with what you're trying to do. You'll need to get a jquery representation by using $(this) instead.

Categories

Resources