how can i add an attribute onClick oto my links generated automatically? - javascript

I would like to add an attribute onClick to my links generated automatically with jquery.
I select the parent div and then search if it has a link child, then add the attribute onClick.
It works on localhost but not on server
there is my code :
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function () {
if ($(this).children('a').hasClass('holder_notify_drop_link')) {
$(this).on('click', function (e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick', "openFrame('" + url + "','yes')");
e.preventDefault();
});
};)
};
How can i do this ?

Make sure you include jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
e.preventDefault();
});
};
)};
});

Here's a working example http://jsfiddle.net/g248G/.
HTML:
<div class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://stackoverflow.com">Stackoverflow.com</a>
</div>
<ul>
<li class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://google.com">Google.com</a>
</li>
</ul>
Javascript:
function openFrame(URL, option) {
window.open(URL);
}
$(document).ready(function() {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
$(this).children('a').each(function() {
var $link = $(this);
if ($link.hasClass('holder_notify_drop_link')) {
var URL = $link.attr('href');
$link.on('click', function(event) {
event.preventDefault();
openFrame(URL, 'yes');
});
}
});
});
});

Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
ev.preventDefault();
openFrame($(this).prop('href'), 'yes');
});

Related

I have a problem with javascript $ .get (URL, callback);

Thanks for the support! - Sory, my english is bad!
I use this code to get the DOM component from the page entry to display on the homepage.
When I click on open-ajax, it loads the DOM from the entrypage and display in ajax-outer, when clicked on ajax-overlay, it will delete the DOM.
But I discovered an error, if I clicked on an open-ajax link and clicked on ajax-overlay immediately, get () will still load the DOM and display in ajax-outer.
It seems that ajax-overlay is unable to stop get ()
How can I optimize the code?
Html from Homepage:
<div class="main_content">
<a class="open-ajax" href="/link/101">1</a>
...
<a class="open-ajax" href="/link/10n">n</a>
</div>
<div class="ajax-wrap">
<div class="ajax-overlay"></div>
<div class="ajax-outer"></div>
</div>
Html from Entry:
<div class="coupon_content">
<div class="abc">
....
</div>
</div>
Javascript:
$('.main_content').on('click', '.open-ajax', function(e) {
var gethref = $(this).attr('href');
e.preventDefault();
$('.ajax-wrap').addClass('active');
$.get(gethref, function(sch) {
$('.coupon_content', sch).each(function() {
$('.ajax-outer').append($(this).html());
$("body").addClass('noscroll');
});
});
});
$('.ajax-overlay').click(function(e) {
$('.ajax-wrap').removeClass('active');
$('.ajax-outer').children().remove();
$("body").removeClass('noscroll');
});
Ví dụ tương tự : https://dribbble.com/shots
You can't prevent a ajax request but you can prevent the appending using a global variable
var canAppend = true;
$('.main_content').on('click', '.open-ajax', function(e) {
var gethref = $(this).attr('href');
e.preventDefault();
$('.ajax-wrap').addClass('active');
$.get(gethref, function(sch) {
if(canAppend) {
$('.coupon_content', sch).each(function() {
$('.ajax-outer').append($(this).html());
$("body").addClass('noscroll');
canAppend = true;
});
}
});
});
$('.ajax-overlay').click(function(e) {
$('.ajax-wrap').removeClass('active');
$('.ajax-outer').children().remove();
$("body").removeClass('noscroll');
canAppend = false;
});
You could hide the ajax-overlay when you click open-ajax and show it in the success callback, this way you make sure that the overlay will not be clicked until all the code is loaded:
$('.main_content').on('click', '.open-ajax', function(e) {
e.preventDefault();
var gethref = $(this).attr('href');
$('.ajax-wrap').addClass('active');
$('.ajax-overlay').hide();
$.get(gethref, function(sch) {
$('.coupon_content', sch).each(function() {
$('.ajax-outer').append($(this).html());
$("body").addClass('noscroll');
$('.ajax-overlay').show();
});
});
});

Function gets called twice for each click

The $(".actionsAdListnTo").click function is getting fired twice.
I tried various solutions posted in StackOverflow but nothing worked.
What is the reason of twice firing any pointers please.
How to avoid this?
$(".actionsAdListnTo").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var selectedListinsCount = selected_Listings.length;
var SelectedMlsnums = selected_Listings.join();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
//*********** To Cart Functionality
if (ddlselectedVal == 'Tocart') {
if (selectedListinsCount > 500) {
if ($('#errmesg').length == 0) {
$('.messageCenter').append('<span id="errmesg" class ="errmesg"> <span class="messageIcon"></span><span>The maximum number of listings you may select To Add to cart is 500.</span></span>');
return false;
}
} else {
$.post(urlstring,
function (data) {
$(window.open(urlstring, '_blank', 'width=750, height=400')).load(function (e) {
var $formCopy = $("#frmPostToEmailReports").clone();
$($formCopy).append('<input id="SelectedMlsnums" name="SelectedMlsnums" type="hidden" value="' + SelectedMlsnums + '">');
// Here "this" will be the popup window. insert a form element into the popup window.
$(this.document).find("#divfrmInfo").html($formCopy);
e.preventDefault();
});
});
}
}
}
});
HTML :
<div class="actionsAdListnTo">
<span> Add Listing To</span>
<ul id="actionsAdListnTo" class="ddlAddListinTo" style="display: block;">
<li id="Tocart">To CART</li>
<li id="Toportal">To Portal</li>
<li id="SaveListings">Save Listing</li>
</ul>
</div>
The click on li bubbles to its parents, one of them being <div class="actionsAdListnTo">, so the parent's click handler is also called. Try to stop propagation of the click on li:
$(".ddlAddListinTo li").click(function (e) {
e.stopPropagation();
...
In this case it looks it would be more correct to target the link only for the toggle and not the outer div. Be as specific with your selectors as possibe, similar to this:
$(".actionsAdListnTo a#select").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
If you want to be more specific without an id using the structure, you could do it simlar to:
$(".actionsAdListnTo > span:first > a").click(function (e) {
$('#actionsAdListnTo').slideToggle();
});
Anyway, the way your HTML is structured there is no need to have the toggle triggered by the div as only the link should react to it.
DEMO - Getting more specific with the selector
What I see here is that you are defining two events in the same place, the second one on a child.
$(".actionsAdListnTo").click( function(e){
...
});
$(".ddlAddListinTo li").click(function () {
...
})
Maybe you can use e.sTopPropagation() in the second one, or e.preventDefault()

Create onclick method with href

I want to create AJAX versions of links where possible. For this I want to have a function replaceLinks which create a onClick handler for each link on the page which then calls ajaxPageWSM(href). I have this:
function replaceLinks() {
$("a").click(function() {
...
});
}
How can I access the href inside the function?
var a_href = $(this).attr('href');
You can get the href like this:
function replaceLinks() {
$("a").click(function() {
var href = $(this).attr("href");
});
}
I'm not sure you even need anything other than this.href. So like:
function replaceLinks() {
$("a").click(function() {
var href = this.href;
});
}
Try this:
function replaceLinks() {
$("a").on("click", function(event) {
var href=event.currentTarget.href;
});
}

Change the OnClick event using Javascript

I have an HTML anchor tag like
<a href="anchorid" onclick="callEvent(1)">
Here I call the Javascript function like
<script>
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
document.getElementById("anchorid").onClick = function () { callEvent(0) }; // BY using this code, update the onclick callEvent(0), like toggle
}
</script>
I wants to update the anchor tag like
<a href="anchorid" onclick="callEvent(0)">
When using this code, it is not updating as per my requirement.
document.getElementById("anchorid").onClick = function () { callEvent(0) };
How do I get it to update?
for using document.getElementById("anchorid").. you need to have id in your element, which you currently dont have, try doing:
//add id to your anchor
<a href="javascript:void(0);" id="anchorid" onclick="return callEvent(1);">
test
</a>
and js
<script type="text/javascript">
function callEvent(num) {
alert("Anchor ID is - "+num);
document.getElementById('anchorid').onclick = function () { callEvent(0) };
}
</script>
Store the toggle value in tag itself and then use.
<script>
function callEvent(val) {
var val = document.getElementById("myId").getAttribute('data-val');
alert(val);
// toggle value
val = val==1?0:1;
document.getElementById("myId").setAttribute('data-val',val);
}
</script>
<a id="myId" data-val="0" onClick="callEvent()">Click</a>
here value is stored in data-val value so that is toggled in the callEvent function itself, so no need to rebind the event.
See Example fiddle
try:
document.getElementById("anchorid").onclick
Better:
document.getElementById("anchorid").addEvenetListener('click', function(){
});
Tested: http://jsfiddle.net/Yca5W/
document.getElementById("anchorid").onclick =
function () {
alert("clicked");
};
if you only change parameter of calling function then you dont have to change complete event. You can do it like this:
HTML
<a id="anchorid" href="#">click me !</a>
JS
<script>
var anchor = 1;
document.getElementById("anchorid").onclick = function(){
alert("Anchor ID is: " + anchor);
anchor = anchor == 1 ? 0 : 1; //toggle 0 and 1
}
<script>
try This:
var anchor= document.getElementById('anchorid');
anchor.addEventListener('click', function() {
callEvent(0);
});
OR
$( "#anchorid" ).click(function() {
callEvent(0);
});
if you only want changes passing parameter from 1 to 0 or vice verse then do this one:
<input type="hidden" name="para" id="para" value="1" >
<a href="anchorid" onclick="callEvent($('#para').val())">
$( "#anchorid" ).click(function() {
if ($('#para').val()==1) {
$('#para').val(0)
} else {
$('#para').val(1)
}
});
try this, it may solve your problem demo Fiddle
Add id="anchorid" to your anchor tag
When you click it next time it will callEvent by argument 0,
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
var ele = document.getElementById("anchorid");
ele.setAttribute("onclick","callEvent(0)");
}
It will update your link like you wanted
<a href="anchorid" id="anchorid" onclick="callEvent(0)">

Jquery mouseover function not firing

I have this Jquery code:
$(document).ready(function() {
// Do menu mouseovers
$('.bar a').each(function() {
var Link = $(this);
var LinkID = Link.attr("ID");
$('.menu-pop').each(function() {
var PopID = $(this).attr("data-for");
// We have found a match, assign events
if (PopID == LinkID) {
Link.mouseover = (function() {
alert("trucks lol");
});
return;
}
});
});
});
It's for a popup menu I'm writing. The simplified structure of the menu is:
<div class="bar">
<a class="item">Home</a>
<a class="item" id="mnuAnother">Another Link</a>
</div>
<div class="menu-pop" data-for="mnuAnother">
Links and stuff
</div>
I'm expecting it to do the alert when my mouse goes over the "Another" link, but at present it throws no errors/no alert.
Any help appreciated.
Did you try
Link.mouseover(function() {
alert("trucks lol");
});
(using jQuery's mouseover function which is a shortcut for binding the mouseover event)
See: http://jsfiddle.net/rQ72v/
Change this:
Link.mouseover = (function() {
alert("trucks lol");
});
to this:
Link.mouseover(function() {
alert("trucks lol");
});
Link.mouseover = doesn't really make any sense.
Perhaps Link.onmouseover = would work (or would you need Link[0].onmouseover =?) in terms of raw JavaScript.
But, it's much better to use jQuery's .mouseover().
I would replace the
// ...
$('.bar a').each(function() {
var Link = $(this);
// ...
by something line
// ...
$('.bar a').each(function(item) {
var Link = $(item);
// ...

Categories