.click jQuery function not working - javascript

I've never run into this problem... can someone help me with this?
my ".click" jQuery function is not calling. I'm confident that it's my syntax, but I cannot find the mistake!
Working jsFiddle here: http://jsfiddle.net/cQ43Z/
HTML:
<a id = 'emailoff' href = "" target = "_blank">
<img id= 'email-btn' src="http://www.clker.com/cliparts/2/a/r/5/G/O/save-button-png-hi.png"/>
</a>
Javascript:
$('#email-btn').click(function(){
console.log('email btn clicked');
});

Your img tag has an id of save-btn while you are attaching the click event to email-btn. Either you didn't post all your code or you named your button wrong.
EDIT: Now the problem is that your a tag is redirecting the user off the page. If you don't want that to happen then you should set the href attribute to javascript:;.
<a id = 'emailoff' href = "javascript:;">
You don't need the target attribute either. And unless you are using the a tag for something else, it is entirely unnecessary itself.

Related

href and js to be worked work together on html

I am trying to open my href link and setting the padding of container of web page at same time.
My code is as
<a href="/Link1/" onclick="return SizeOf(); " >LinkText</a>
function SizeOf() {
document.getElementById("contain1").style.padding = "000px 150px 00px 210px";
}
But for now either of them working.Either I can open my page or I can set the paddings using CSS.I want to do the both things i.e. open my page and set padding as well.
Please help me with this.
Thanks
I encountered the same problem before. The way I deal with it is to put the href stuff inside the function as well, otherwise the click can only trigger either href or the function.
Please try the following, or similar:
LinkText
function SizeOf() {
document.getElementById("contain1").style.padding = "...";
window.location.href = '/Link1/';
}
Use mousedown it will trigger before redirect the link.so both thing's will append
function SizeOf() {
document.getElementById("contain1").style.padding = "000px 150px 00px 210px";
}
<a href="/Link1/" onmousedown="SizeOf() " target="_top" >LinkText</a>
<p id="contain1">contain</p>

how to call or display a div by changing url using href?

i am trying to show a div which is currently hide and inside body tag.by changing url using anchor tag attribute href.Like below---
<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
when i click on this anchor tag my url will definitely changed.and based on url i wants to display a div.
my js code...
function openCity() {
if (window.location.hash == "managevendors") {
$("#managevendors").show();
}
}
i dont know why this is not working.but i teide with different way like below..
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>
and js code.....
function openCity()
{
if (window.location.hash == "#managevendors") {
$("#managevendors").show();
}
}
but i dont want the # sing,how can i solve it.help me experience brothers.thanks in advance.
You must use the hash if you expect the navigation to work. Once you do that, you don't need to check for it, you can just show the section:
$("#ai").on("click", openCity);
function openCity() {
// The only reason this code is running is because the link was clicked.
// No need to test for it.
$("#managevendors").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You have to include the hash in the href for navigation to work -->
<a id="ai" href="#managevendors" class="tablink">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
I think the problem here is that you are using an anchor tag when you should be using a button. The reason the first way is not working is due to the page refreshing when you click the link.
Try changing your <a> to a <button>
From what I understand, you most likely need the href="#xyz" with a hash. This will keep clientside logic active without trying to solve the url and take a detour to the server for nothing. If you're going to capture that part, keep it local.
I suggest to remove the onclick handler from HTML. To capture the link you can use jQuery to keep your HTML "clean". If you must, for some odd reason, by all means you can reference onclick="openCity(this)", so the element you click on is passed directly to openCity.
// vanilla
function openCity(element){
var href = element.getAttribute('href'), // expecting a hash here
id = href.substr(1), // remove the hash
target = document.getElementById(id);
target.className += " active";
return false;
}
As Scott suggests with jQuery:
//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);
Then the function can be made dynamic by referencing the href from the clicked element:
function openCity(ev){
var el = $(ev.currentTarget),
id = el.prop('href'), // expecting a hash here
target = $(id);
// since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
ev.preventDefault();
target.addClass('active');
}
If the id was not found on the page, this will void silently.
Now if you want to work with the url as entry point, note that this will only happen on load event => share a link and someone clicks on it (with the #xyz attached) or type directly in the address bar.
// 1. bind the event
$(window).load(function(){
/*loadCity defined here or outside*/
loadCity();
});
// 2. define what happens
function loadCity(){
var id = window.location.hash, // expecting a hash here
target = $(id);
target.addClass('active');
}
Since this solution only solves state of an element, the actual show/hide part can be made in CSS. Very simple as you probably already did or with animations, transitions and so on.
.city { display: none; }
.city.active { display: block; }

how to call child anchor click on parent div click

I have multiple instances of
<div class="picOuterDiv">
<a href="examplepage.php?var=1" class="iframe" > page one </a>
</div>
<div class="picOuterDiv">
<a href="examplepage.php?var=2" class="iframe" > page two </a>
</div>
Now I am using jQuery colorbox plugin to create Lightbox's. The lightBox opens when i click the anchor element, The anchor element with the class iframe. It works fine till here, using
$(".iframe").colorbox({iframe:true, width:"646", height:"675"});
What I want is to open the colorbox when I click the parent div. I used the following code to trigger anchor element href when div was clicked, but apparently the href alone wasnt enough, the element clicked should have the class "iframe" . So its not working with this code.
$('.picOuterDiv').each(function(){
$(this).on('click', function(){
location.href = $(this).find('a').attr('href');
});
});
So can anybody help me on how I can make this work ? I hope the Problem is clear. Thank you in advance.
UPDATE: http://jsfiddle.net/VhkFN/3/
$('.picOuterDiv').click(function() {
window.location.href=$(this).find('a').attr('href');
});​
There are a couple issues with your fiddle. First "var arr[]" is not correct. Second, the hyperlink doesn't have any onclick property, so triggering a click won't do much. You need to grab its href attribute instead.
Demo: http://jsfiddle.net/VhkFN/4/
This was what worked for me. As i said i was using jquery colorbox.
$(".picOuterDiv").click(function () {
var anchorHref = $(this).find('a').attr('href');
$(this).colorbox ({iframe:true, width:"646", height:"675", href: anchorHref});
});

Set onclick of <a> using JavaScript

I want to change all the links in a div such that they no longer refer to a page, but run a JavaScript function when being clicked. To do so, I wrote this function:
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
$div = $(htmlString).children("div#myDiv");
$div.children("a").each(function(i, element){toJavascriptLinks(element)});
document.getElementById("targetDiv").innerHTML = $div[0].innerHTML;
}
calling this function:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){console.log('Yeah!')};
console.log(element);
}
Now, when I run buildPageInDiv, 'string' is printed on the console, all the "href" are changed to "#" and for every <a> within the div the console prints the element:
<a href="#">
No sign of the onclick here, and clicking on the link does not show anything on the console.
What am I missing here?
Edit:
I was seeking in the wrong place. The problem was that I was running toJavascriptLinks(element) before attaching the innerHTML to targetDiv. That was no problem for the href attribute, but it was for the onclick attribute. Solution is simply to put it in targetDiv first and than run toJavascriptLinks(element) on targetDiv :
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
var content = $(htmlString).children("div#myDiv")[0].innerHTML;
document.getElementById("targetDiv").innerHTML = content;
$("div#targetDiv").children("a").each(function(i, element) toJavascriptLinks(element)});
}
Although the problem was not in the code I originally posted, the comprehensive answers below led me to the solution.
First: All type of selectors in jQuery, start with the dollar sign and parentheses: $()
Secondly: you need to close your statements with ;
Lastly: it is good practice to define your functions BEFORE you call them, instead of relying on javascript to hoist them to the top for you. This will also make jslint validate, whereas the other way round wouldn't!
So your code without your errors would look like:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){alert('Yeah!');};
console.log(element);
}
$('div').children("a").each(function(i, element){toJavascriptLinks(element);});
See this fiddle for a working demo.
Good Luck!!
ABOUT YOUR UPDATED QUESTION:
That's quite an update to your question.
You don't see your onclick in console.log because you set the onclick event in the dom. If you wanted to see the onclick in console.log, you would add the function STRING using:
element.setAttribute('onclick', 'your function string');
Suppose in your html you have:
<a id="link_a" href="http://www.google.com">link 1</a>
<a id="link_b" href="http://www.duckduckgo.com">link 2</a>
And you have this javascript:
var lnkA=document.getElementById("link_a");
var lnkB=document.getElementById("link_b");
lnkA.onclick=function(){alert(this.innerHTML);};
lnkB.setAttribute('onclick','alert(this.innerHTML);');
console.log(lnkA.outerHTML);
console.log(lnkB.outerHTML);
Then console.log will contain:
<a id="link_a" href="http://www.google.com">link 1</a>
<a onclick="alert(this.innerHTML);" id="link_b" href="http://www.duckduckgo.com">link 2</a>
See this fiddle for a live example of this explanation.
I also think you are already using some form of jQuery (without you knowing it) because of your use of .children("div#myDiv"). To my knowledge this no plain vanilla javascript. And I think both plain vanilla javascript and jQuery would not select those divs with id 'myDiv' out of a plain html-string, so the code in your update would not do the job.
Finally, to adjust my answer to your updated question and expectation of the onclick-event being visible in the parsed html-source:
var htmlString='<div id="myDiv">link 1link 2</div><div id="otherDiv">link 3link 4</div>';
function toJavascriptLinks(element){
element.href="#";
element.setAttribute('onclick','console.log("Yeah!");');
console.log(element.outerHTML);
}
//no innerHTML on documentFragment allowed, yet on it's children it's allowed
var frag = document.createDocumentFragment().appendChild( document.createElement('div') );
frag.innerHTML=htmlString;
var $div = $(frag).children('div#myDiv');
$($div).children("a").each(function(i, element){toJavascriptLinks(element);});
var outp=document.getElementById("output");
outp.innerHTML=frag.innerHTML;
See this updated fiddle to see it in action.
That leaves the question: why on earth are you placing 'ninja' $-signs front of your variable names?
That's just the way the debugger displays an HTML element. It doesn't show all attributes - especially since you are setting the DOM property onclick to a function reference, which can't be displayed as the HTML attribute onclick which takes a string (which AFAIK can't be set with JavaScript see Luc's comment).
Try console.log(element.onclick); instead, it should display something like function() {...}.
Or doesn't the event handle work?
BTW, any reason you don't use jQuery to set the href and the handler?
$div.children("a").attr('href', '#').click(function(){console.log('Yeah!')});
One more thing: In most consoles you can click on <a href="#"> and it will display the DOM properties, which should include the event handler.
I would really use jQuery for this, it's quite simple.
​$(function() {
$("div > a ").attr("href", "#").click(function(e) {
e.preventDefault();
doSomething();
});
});
var doSomething = function() {
alert("Woah, it works!");
}
See the following jsfiddle for it in action: http://jsfiddle.net/SsXtt/1/
Are you sure the element is correct? This works for me.
<a id="mylink">Test</a>
<script>
document.getElementById("mylink").onclick = function() {
alert("Works");
};
</script>
Function needs to be inside a string, try adding quotes?

javascript onclick failing on a function call

I have this html...
<a onclick="search.analysisSelect('2');" href="javascript:void(0);">A Product</a>
...And whenever I click that link in the browser (IE, FF, and Chrome), it fails. It tells me that the function does not exist. However, if I type that exact function call into the console of firebug, it runs fine. So the function does exist.
Exact error message: "search.analysisSelect is not a function"
I have recently changed the "search" object name to "searchTab" and the onclick works fine.
Why is the onclick failing for the search object? I am baffled...
Here is the search object. This is stored in a separate js file loaded when the page loads.
var search = {
analysisSelect: function(pub) {
$("#tabs").tabs("select", "#analysis");
analysisGrid.refreshSlickGrid(pub, '0', '1', '0');
}
};
Oh, I forgot to mention that I also have an init() funciton defined in the search object, which is called on an onclick event for another html element, and that fires off with no issues. Wtf...
Where did you define search.analysisSelect()? It should be defined before the anchor tag.
generally using inline javascripts is not a good idea, consider using an external javascript file and bind that function to the anchor onclick event like this:
window.onload = function() { // ensures that the document is loaded before finding the anchor element
// assign an Id to the anchor tag like this: <a id="idOfAnchorTag" href="#">A Product</a>
var elem = getElementById('idOfAnchorTag');
elem.onclick = function() {
search.analysisSelect('2');
}
}
There is some strange javascript voodoo going on in the inline event handler. search is not being resolved to window.search, it is hitting something else and I don't know what it is.
See http://jsfiddle.net/yPhZ8/
However, I can tell you how to fix it. Use window.search instead.
<a onclick="window.search.analysisSelect('2');" href="javascript:void(0);">A Product</a>
See: http://jsfiddle.net/yPhZ8/1/
I just had this exact problem today. Turns out, you can't have an HTML element with an ID the same as the function.
Don't ask me why, I'd just say it has something to do with extremely lazy parsing.
My Example:
<dd style="margin-left: 2px;"><input type="button" name="info[add_benefit]" id="add_benefit" value="{L_ADD_BENEFIT}" class="button2"
style="width: 100%;" onclick="add_benefit();" /> </dd>
The onclick method would return an error saying that the function didn't exist. Apparently it thought the button itself was the function, but the button was a button, hence the error.

Categories

Resources