Javascript event accessing when there is another parameter - javascript

I am working on a feature where if you click a blurb link, it will display the full description in a preview window; much like the search result preview in search engines, like Google.
I need to pass both the full description text and the event to the handling function so the function knows what to display and where to display (under the blurb).
My question is that what should I pass to the function. Currently I have below and it's not working:
blurb text here
function javascript:DisplayFullDescription(e, fullText){
//find out mouse click position
//display a preview window (div) with description there
}

If you're not using HTML5, personally, I would create a hidden element for the full text with display:none, which I would assign as data to each applicable element, and use that info on click
<a class="clickable" href="#">blurb text here<span style="display:none">blah blah description goes here</span></a>
$('a.clickable').each(function() {
$(this).data('fulltext',$(this).find('span').remove().text());
}).click(function(event) {
event.preventDefault();
$('body').append('<div>'+$(this).data('fulltext')+'</div>');
})

It would be much easier to use jQuery to bind the event handlers, and an HTML5 data-* attribute to store the full text, rather than using onclick attributes.
HTML:
blurb text here
jQuery/JavaScript:
$('a').click(function(e) {
DisplayFullDescription(e, $(this).data('fulltext'));
e.preventDefault();
});
function DisplayFullDescription(e, fullText){
//find out mouse click position
//display a preview window (div) with description there
}

<a id="someID" href="#" data-fulltext="blah blah description goes here">blurb text here</a>
<script>
var element = document.getElementById('someID'); // grab the element by id. (simple for this demo)
element.onclick = DisplayFullDescription; // attach the event handler to the onclick function
function DisplayFullDescription(e) { // because we attached the handler above the Event is passed as the first argument to the function (handler)
var description = this.getAttribute('data-fulltext'); // 'this' now references the element in which the onclick was invoked.
alert(description);
}
</script>
You can try this above and see if it meets your needs.
Considerations:
- This does not need jQuery library to function (it would be overkill to use it for just this)
- This will work cross browser (old and modern)
- This has nothing to do with HTML5 (which is cool... but again, overkill and limiting)
- data-* can be accessed using getAttribute() and does not rely on the element.dataset being available.
However it would benefit you to read up a bit more on Events

Related

How to disable a html link to instead call a JS function?

Having a text with annotations linking my text to dbpedia, I wanted to know if an effective way exists in Javascript for, by clicking on the link, to display a div with selected dbpedia information, rather than arriving on the page on the link ?
I am looking for some kind of "display none" on the link to allow me to display my div. I can not find this method, does it exist?
Furthermore, the links in my text are generated dynamically thanks to an Ajax request, and that they do not have id or class.
Here is one of my links in my text:
<a href="http://dbpedia.org/resource/Lorem_ipsum" title="http://dbpedia.org/resource/Lorem_ipsum" target="_blank" on>Lorem Ipsum</a>
Because the links are dynamically created you should use event delegation to get them. You can use an attribute selector to look only for links that start with a particular substring. Then use preventDefault to disable the link prior to using AJAX to grab the information and add it to a modal.
$(document).on('click', 'a[href^="http://dbpedia.org"]', function (e) {
e.preventDefault();
// load data from your source
});
DEMO
The non-jQuery version would look something like this:
document.addEventListener('click', handleClick, false);
function handleClick(e) {
const el = e.target;
if (el.tagName === 'A' && el.href.startsWith('http://dbpedia.org')) {
e.preventDefault();
// Do things
}
}
DEMO

Alter the text in the p tags

I want to alter the text in the p tags to gain (upon clicking the text) the properties set by the attribution class.
Here is the HTML:
<p onclick="function">Hello</p>
CSS:
.attribution{
color:blue;
font-weight:bold;
}
Javascript:
var main = function() {
$('<p>').text('.attribution');
};
$(document).ready(main);
Thank You!
<p onclick="function">Hello</p>
You:
Have to use the name of the function, not the keyword function which creates a new function.
Have to actually call the function, by appending () to the variable name
Shouldn't use intrinsic event attributes at all. Bind event handlers with JavaScript.
So
<p>Hello</p>
<script>
$("p").on("click", main);
</script>
var main = function() {
$('<p>').text('.attribution');
};
$(document).ready(main);
You:
Should use a function declaration (since it plays nicely with debuggers)
Need to select the existing paragraph instead of creating (and promptly discarding) a new one)
Add attribution to the classes on the element instead of replacing the text content of it with the phrase ".attribution"
Not call the function on DOM ready when you want it to be called when something is clicked
Such
function main() {
$('p').addClass('attribution');
};
As an aside, paragraphs are not designed to be interactive. While you can click on them with a mouse pointer, nothing encourages people to do so, they are outside the normal focus list (so people who don't use a mouse can't tab to them) and don't show up in screen readers as something that should be clicked on. Use appropriate markup (perhaps a button).
Okay, since your loading JQuery why no use its methods for handling click events and changing the css properties.
$( "p" ).on( "click", function() {
$(this).addClass('attribution');
});
1) You are not actually hooking any callback function to onclick event. You need to specifiy what function you want to be executed on click.
So:
HTML:
<p onclick="addClass(event)">Hello</p>
JavaScript:
function addClass(evt){
evt.target.classList.add('attribution');
}
jQuery alternative:
var main = function(){
$("p").click(function(){
$(this).addClass("attribution");
});
}
$(document).ready(function(){
main();
});

Binding event with mouseover on an iframe that sits on my page with a src that contains

I have some third party iframes that sit on my page and I want to capture when a user mousesover them ONLY if the src of those iframes contain either twitter or facebook anywhere in the src text. Since I can't capture the clicks (I can with their custom methods, I want to keep code completely seperate). I want to capture when a user mouses into an iframe (that sits on my page, is not brought in by them). The "SRC" of the iframe is outside my site, but the actually call is in my page. Any ideas?
ala:
var _self = this;
$("iframe src").filter('/facebook|twitter/')
.mouseover(function(event){
event.stopPropagation();
_self.somemethodcall();
});
or something like:
var _self = this;
$('iframe').filter(function() {
return $(this).attr('src').match(/facebook|twitter/);
}).bind("mouseover", function(event) {
event.stopPropagation();
_self.somemethodcall();
});
It would look like this:
var a = /facebook|twitter/;
$('iframe').live('mouseover',
function () {
if(a.test($(this).attr('src'))){
alert('Found it!');
}
}
);​
First we throw the Regular Expression in a variable named a. Then upon hovering the iframe we test the src of the iframe to our Regular Expression, which will return true if the value of src contains either facebook or twitter.
A working example: http://jsfiddle.net/2PZ2c/
(third one is the one with the google.com source)
Readables:
http://api.jquery.com/hover/
http://www.w3schools.com/jsref/jsref_regexp_test.asp
Side note:
This solution will also work with other handlers like mouseenter, mouseleave, etc.
Edit:
I've edited my code to use the .live() function instead. This function will attach an event handler to both current elements as future ones.
Example: http://jsfiddle.net/2PZ2c/1/
Source: http://api.jquery.com/live/

Is there any callback function on click?

Let's say I have the following link:
<a href="#shippingaddress" onclick="return validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);" >
EDIT
i am using multi page approach to show different section(divs) as a page
in that validate function I am validating the form and if everything is ok then displaying a hidden <div> and after the <div> is visible <spans> are getting applied by jquery mobile framework, untill and unless that div is hidden there is no span, but as that div become visible jquery mobile gets applied on it and appended some spans..i need to access this spans :
<span>blah</span>
So I want to change the text of this <span> after the click event, because the <span> is displayed after the click event.
So is there any way to do this?
In your validate function you can do this:
<div id="someDiv" style="display:none">
<span id="someSpan"></span>
</div>
<script type="text/javascript">
function validateBillingAddress() {
var valid = true;
... // do whatever you need to validate your input here and update valid variable
if (valid) {
$('#someDiv').show();
// if the validation is succesful invoke some function in the framework here
$.ajax({
...
success: function() {
//append the span to the div here
$(#someDiv').append('The span HTML content');
},
...
});
}
}
</script>
You could actually embed the validateBillingAddress into another function, containing the "callback" line as well
function doValidate( event ) {
validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);
$('#spanElement').text( 'new text' );
}
And then
<a onclick="return doValidate( event );" >
Would be even better if you avoided using the onclick property in favor of a non-invasive event handling like
$('#aElement').click( function( e ) {
doValidate( e );
});
Do not use inline javascript...
$("#validate").click(function(){
// validate billing address
});
<a id="validate">Validate</a>
To create a span and attach a listener to it, then append to the div:
$("<span />").click(function(){
$(this).text("New Text");
}).appendTo("#divToShow");
Edit:
Since you haven't provided much information, the only thing I can help you out is:
1- To access all spans within the div, you do:
$("#myDivId span")
2- To access only spans that are direct children of the div, you do:
$("#myDivId > span")
3- To access only the last span within the div, you do:
$("#myDivId span:last")
More than that, only if you provide some actual generated code

jQuery DIV click, with anchors

To make click-able divs, I do:
<div class="clickable" url="http://google.com">
blah blah
</div>
and then
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
<a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called
This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.
Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
See event.preventDefault() vs. return false for details on return false vs. preventDefault.
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) {
event.preventDefault();
$('div.link1').show();
//whatever else you want to do
});
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) {
event.preventDefault();
window.location = $(this).attr("url");
});
<div class="info">
<h2>Takvim</h2>
Click Me !
</div>
$(document).delegate("div.info", "click", function() {
window.location = $(this).find("a").attr("href");
});

Categories

Resources