Setting click to not created elements - javascript

this is my first question here and I hope I'm asking it correct.
I'm making an userscript. The website has a chat and when a user for example clicks a message it should copy it. The website has removed right click and selecting. I know how to copy the message, but I don't know how to add the click feature part.
This is the code I have so far:
$(document).ready(function(){
$('.msg').click(function(){
$('#someinput').val($(this).text())
.select();
document.execCommand('copy');
});
});
This gives me the error Cannot read property 'click' of null, and I guess that is because the chat message isn't created yet. How do I fix this?

You must use jQuery event delegation: http://learn.jquery.com/events/event-delegation
If your .msg elements are inside a container you can write
$(document).ready(function() {
$('#container').on('click', '.msg', function() {
// your click function
});
});

Related

Can't detect checkbox change when adding on document load

I'm a little stuck on this. I have a javascript function that, on page load, generates a form:
All the checkboxes have the class 'cls-select'. I am trying to then run another function (I've put a console.log in for now) when any of these checkbox states are changed but it's not detecting any changes.
$(function() {
FormGenerate();
$('.cls-select').change(console.log('Something changed...'));
// ...
});
When the page is first opened, the log message appears. But, no matter what is checked / unchecked, no additional log entries appears.
Can some one explain to me why this occurs? I'm guessing it's because when the .js file is loaded by the browser, there are no checkboxes with cls-select that exist on the page so there is nothing 'there' to fire the trigger.
Is there a way around this without having to start over? Any help / advice is greatly appreciated.
Your logic is assigning the result of console.log('Something changed...') execution as event handler and that's not what you are expecting to do.
Change your code by
$('.cls-select').change(function(){
console.log('Something changed...');
});
I think it happens because when you trying to set 'onchange' event for checkboxes, they didn't appear yet. So you should use jQuery 'on' like this:
$( 'body' ).on( 'change', '.cls-select', function() {
console.log('changes!');
});
There is a problem in your code you should do like this
$(function() {
FormGenerate();
$('.cls-select').change(function(){
console.log('Something changed...');
});
});

Change attribute of twitter link

I'm trying to change the data-url with jQuery. Currently my code looks like this.
<div id="twitterButton" title="Tweet it on Twitter">Tweet</div>
<script type="text/javascript">
$(document).ready(function () {
$('#twitterButton').click(function () {
$('#tweet').attr("data-url", "https://www.google.com/");
});
});</script>
As you can see I left the url-data blank so I could be sure it is only getting set in the jQuery. However whenever I click the tweet button it always opens the window with the link for the current page that I was on. Can someone explain how I can set it to be something else via jQuery or javascript?
You should use .data() for controlling data attributes. As Daniele states in that answer, you must also stop the event propogation on the a element using preventDefault().
$('#twitterButton').click(function (e) {
$('#tweet').data('url',"https://www.google.com");
e.preventDefault();
});
You must call the preventDefault() method to stop the propagation of the click event on the child a element:
Try this code:
$('#twitterButton').click(function (e) {
$('#tweet').attr("data-url", "https://www.google.com/");
e.preventDefault();
});
Good code
D.

How to make a div click-through but hover-able?

I need to make a div so that when the cursor hovers over it then I can detect it (using javascript) but I want to make it so that you can click through the div to the elements underneath. Is there a way to do this?
Thanks
Edit
As far as I'm aware, and through my quick searches, I do not believe that you are able to do this, if you can it wouldn't be easy and or very practical I wouldn't think.
old
Using jQuery:
$(document).ready(function(){
$("body").on("hover", "div", function(){
//do whatever you want on hover
});
$("body").on("click", "div .child-class", function(){
//do whatever on click
});
});
If this doesn't answer your question and do what you want, let me know what more specifically why it doesn't.
There are multiple solutions for this depending on your problem.
I will start with some assumptions:
1. You are the owner of the page (you know what happens there);
2. You know what element is beneath the clicked element.
For this case check this code:
//function executed when you click on element with id: beneath
function clickOnBeneath() {
alert("beneath click");
}
//function executed when you click on element with id: above
function clickOnAbove() {
var beneathEl;
beneathEl = document.getElementById("beneath");
beneathEl.click();
}
//attach click event on element with id: above and beneath
function attachClickOnElements() {
var aboveEl,
beneathEl;
aboveEl = document.getElementById("above");
aboveEl.addEventListener("click", clickOnAbove, false);
beneathEl = document.getElementById("beneath");
beneathEl.addEventListener("click", clickOnBeneath, false);
}
attachClickOnElements();
and also working example: http://jsfiddle.net/darkyndy/xRupb/
If you don't know what element is beneath it then I will try to find some code as I wrote a couple of years back something like this, as start point you can check getClientRects() function that is available on HTML elements (documentation: https://developer.mozilla.org/en-US/docs/DOM/element.getClientRects )

jquery - using event.stopPropagation()

When the document is ready, I'm fetching some datas from the server through post request and I'm filling it in the HTML as tags by append. When you click that tag, a comment textarea will be displayed. When you click in the document section, the textarea will be closed. The problem here is I can't enter the text in the textarea, when I click inside, it is hiding. I tried using event.stopPropagation() but no use.
Here is my jquery code:
$.post("/person/keywords/get/", function(data){
for(i=0; i<data.length; i++)
{
count = count + 1;
$(".keywords-set").append('<div class="keyword-item"><span class="keyword" id="keyword-'+count+'">'+data[i]+'</span><textarea class="comment" id="comment-'+count+'"></textarea></div>');
}
});
$(".keywords-set").on('click', "[id^=keyword]", function(event) {
event.preventDefault();
i = $(this).attr("id");
i = i.split('-').pop();
$("#comment-"+i).show();
return false;
});
$(".comment").click(function(event) {
event.stopPropagation();
});
$(document).click(function() {
$(".comment").hide();
});
For complete HTML and javascript code, please check here: https://gist.github.com/3024186
It is working in jsfiddle
but not in my localhost. Could you tell the reason, why is it so?
Thanks!
UPDATE
I've also tried this
$(".keywords_set").on('click', ".comment", function(event) {
event.stopPropagation();
});
event.stopPropagation() is not working for HTML elements updated through ajax. But is working for normal(already given) elements.
When doing this:
$(".keywords_set").on('click', ".comment", function(event) {
You must understand that you're catching the event in the element ".keywords_set", and there you will be checking if it bubbled up through ".comment"
This means that any other "click" events set between ".keywords_set" and ".comment" will also activate.
doing stop propagation or returning false will only take affect from the bubbling of ".keywords_set" to the document.
You can do this:
$(document).click(function() {
if($(".comment:hover").length==0){
$(".comment").hide();
}
});
Edit: reply to: "Hey, that code works, I don't know how you are doing it by mentioning .comment.length could you be more descriptive about that?"
When you do any jquery selector, an array is returned. so if you do $(".comment") all html nodes with the class ".comment" will be returned to you in a list [obj1, obj2, ..., objn]
When you do $(".comment:hover") you are asking jquery to select you any element with the class "comment" which also have the mouse currently on top of it. Meaning if the length of the list returned by $(".comment:hover") is bigger than zero, then you caught a bubble from a click in a ".comment".
Although either returning false or stoping propagation should also work. (dunno why in your case it is not working, although i didn't look much at the full code)
Edit 2:
i was lazy to read the full code. but when you are setting the click event for the comment, the comment doesn't exist yet. so the new comment you are adding will not be be caught by your click handler. add it inside the ajax callback and it will work :)
Edit 3: one more thing:
you are not getting side effects because the click even you are re-defining only has the the stop propagation, but you should add the stop propagation before returning false in the
$(".keywords_set").on('click', ".comment", function(event) {
because in practice all other comments you have will be proccessing N times the click event that you are adding to be processed multiple times
Since post method is a asynchronous. You are binding $(".comment") before it exist.
moving
$(".comment").click(function(event) {
event.stopPropagation();
});
after
$(".keywords-set").append('<div class="keyword-item"><span class="keyword" id="keyword-'+count+'">'+data[i]+'</span><textarea class="comment" id="comment-'+count+'"></textarea></div>');
should work.

jQuery Toggle on mouseup

I have the following jQuery:
$('#account-menu').hide();
$("#account-link").click(function(e) {
e.preventDefault();
$("#account-menu").toggle();
$("#account-link").toggleClass("selected");
});
What I want to do is check if the user clicks anywhere else onscreen WHILST THE ACCOUNT MENU IS SHOWN BUT not within the account menu itself, and if so then hide the menu. Can anyone help?
Thanks
EDIT:
I had a go at doing this myself like so:
$('#account-menu').hide();
$("#account-link").click(function(e) {
e.preventDefault();
$("#account-menu").toggle('fast');
$("#account-link").toggleClass("selected");
});
$(document).mouseup(function(e) {
var $targ = $(e.target);
// if we are the link or the box, exit early
if ($targ.is('#account-link') || $targ.is('#account-menu')) return;
// if we have a parent who is either, also exit early
if ($targ.closest('#account-link, #account-menu').length) return;
// hide the box, unselect the link
$("#account-link").removeClass("selected");
$("#account-menu").hide('fast');
});
But wanted to see if there was a nicer and much smaller (code-wise) way of doing it.
Use jQuery to hide a DIV when the user clicks outside of it
Maybe something like this...
$('#account-menu').hide();
$('body').click(function(){
$("#account-menu:visible').toggle();
$("#account-link").removeClass("selected");
});
$("#account-link").click(function(e) {
e.preventDefault();
$("#account-menu:not:visible").toggle();
$("#account-link").addClass("selected");
});
UPDATE
So this won't fully work, since the body click triggers when you click the link too. This is a step in the right direction though. G/L
UPDATE #2
I finally got this working over on JSFiddle.net, using the comments from Joseph Le Brech (+1). Check out the live Demo. I could not get the $('body') selector working on there, so I am simulating the body with a div called bodyDiv. It's all commented and working 100%. Happy Coding.

Categories

Resources