I am sort of new to JavaScript and something has been bugging me.
Say I have some code like this:
$('button').on('click', function() {
var id = $(this).attr("id") // id being a file name sans extension
$('.content').load(id + '.php');
});
Everything works just fine, but something in the back of my head tells me that this is bad practice. Any thoughts?
It's fine but you can save some operations using this.id
$('button').on('click', function() {
$('.content').load( this.id +'.php');
});
I like this article here: https://stackoverflow.com/tags/jquery/info
You should not be using the ID attribute for this purpose. Instead, you should use a custom attribute. For instance:
<button data-url="mypage">Click me</button>
Then get that attribute instead of the ID.
Related
This is a "LIKE" system similar to Facebook.
I've got an html layout with multiple links where each one looks something like this when rendered :
<a class="like-comment-link" href="#" data-id="278">
<span class="like-comment"></span></a>
<span class="likes">Bob, John and Peter like this</span>
I'm using AJAX to insert and delete the likes into the database, this is all working great. But I'm having trouble targeting the "likes" class from the ajax script to update the names of the people that liked it.
I basically need something which does the following :
$(this).closest(".likes").find(".likes").load(location.href + " .likes");
I know this doesn't work but I don't know the correct way to code it.
Basically, on a successful like or unlike I need jQuery to find the closest instance of ".likes" to the parent which is ".like-comment-link" and then reload that class only on this element.
EDIT
Including AJAX script
$(document).ready(function(){
$(document).on('click', "a.like-comment-link", function(event) {
event.preventDefault();
var $self = $(this);
var data = {
post_id: $self.data('id'),
nonce: likecom.nonce,
action: 'comment_likes'
};
$self.addClass('loading');
$.post(likecom.ajaxurl, data, function(res) {
if (res.success) {
$self.html(res.data);
$self.siblings(".likes").load(location.href + " .likes");
} else {
alert("It went tits up!");
}
$self.removeClass('loading');
});
});
});
If this is overly complicated I could change target class' name to include the id of the current item like this :
<span class="likes-278">....</span>
But I can't figure out how to concatenate strings in jQuery.
I tried a few things like this :
$(".likes-" + $self.data('id')).load(location.href + " .likes-" + $self.data('id'));
But that obviously didn't work.
Maybe somebody could show me how to correctly formulate this in the AJAX script?
You may try something like this. Since the span is always after the anchor element in your example, you may also use .next() function to locate the element
$('.like-comment-link').on("click",function()
{
if($(this).next("span").hasClass("likes"))
{
$(this).next("span").removeClass("likes");
$(this).next("span").addClass("nolikes");
// Write value to db
}
else
{
$(this).next("span").removeClass("nolikes");
$(this).next("span").addClass("likes");
// Write value to db
}
});
http://jsfiddle.net/3k0vLdt4/3/
Hope it helps doing what you want to do.
My problem is that I got 2 aspx controls generated like this :
<a id="sortByDate" href="javascript:__doPostBack('sortByDate','')">Date</a>
<a id="sortByLastName" href="javascript:__doPostBack('sortByLastName','')">Last name</a>
so those links allow you to sort the results. I'm trying to put this in a combobox instead of using links.
So I made it like this
<select id="sortBySelect" onchange="javascript:sortBy(this);">
<option value="sortByLastName">Last name</option>
<option value="sortByDate">Date</option>
</select>
with this javascript function
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
So when you change the selected element in the combobox I want to trigger the click event on the link to call the dopostback to sort.
It does nothing so far. I tried "click", "onclick", "onClick" and nothing works. Unfortunately, this is for IE quirks mode.
I know, this is really not elegant, but I'm really short in time and I need something quick and dirty. I will make an aspx control eventually to handle this nicely.
Any ideas how I could make this work in ie quirks mode?
Thank you
Try changing the location of the page:
document.location = $("#" + id).attr('href');
why don't you just fire the __doPostBack directly:
function sortBy(sel) {
var id = sel.value;
__doPostBack(id,'');
}
Use:
function sortBy(sel) {
var id = sel.value;
alert($("#" + id).length);//just for conforming that the element exists.
$("#" + id).click();}
Actually, jQuery only triggers any event bound to an element. You are trying to call the href action.
If you don't want to change the markup, you could try this solution.
Otherwise, you will have to change your html markup to bind javascript events & then try triggering it.
Good luck!
Everything works as intended!
JSFiddle proof.
Make sure you have an element with the id sortById and sortByLastName !
JavaScript/jQuery
$(document).ready(function(){
$('#sortByDate').click(function(){
alert('Sort By Date Click Event fired!');
})
});
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
Alternative
Force the window.location change
JavaScript/jQuery
function sortBy(sel) {
var id = sel.value;
window.location = $("#" + id).attr('href');
}
Note: You won't see any change in JSFiddle:
Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
I'm using jquery data() to attach the name of a div I'd like to show when another div (.panel_button) is clicked. I'm doing the attaching of this div's id to the button when the document is ready. Is this an okay way to do this? Or is it too resource intensive and unprofessional-looking?
$(document).ready(function(){
$('#sample_button').data('panel', 'sample_kit_container');
$('#mail_button').data('panel', 'mail_container');
$('#mbillboard_button').data('panel', 'mbillboard_container');
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
$('#' + panel).show();
});
});
Yeah, that should work just fine. As an alternate, you could store the actual element itself (assuming it already exists) rather than finding it each time:
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
Another option would be to store the actual jQuery element in the data property, so no need to do a second selection:
$(function(){
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
});
#thomas, in my opnion, your solution is actually better than those in the other answers.
Including the whole object inside the data attribute may not always work. For example, what if the $('#sample_kit_container') object doesn't exist on load, but rather ofter an ajax load.
...
Only one tiny comment! why don't you call the data object: panelId. It would be more a bit intuitive.
Here is my JQuery Code:
$(function () {
$('[id*=clickbtn]').click(function () {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});
Now the problem is, i have 4 to 5 buttons whose id contains 'clickbtn' when i click the any one of them for first time it works well. But it does not works for second click, any help why is this happening?
[EDIT]:
I tried putting the JQuery on page and it worked.. But wnt to know why it does not work on when i put the same on .JS file?
Yes, the result of your event handlers depends very much on the content of your event handlers. If you'd like to share with us the rest of the code we might be able to help. For now the answer is: working as intended
jsFiddle
If your clicks only work on the first try, then I can assure you that it is only the missing code which is to blame. Provide the contents of oWnd.setUrl and oWnd.show and we might be able to help.
Your wildcard selector is wrong. It should be
$("[id$=clickbtn]")
Try this:
$('input[ID*="Button"]')
OR
First set class="btn" to all buttons you want to do this action then
$(function() {
$('.btn').click(function() {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});
I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps