How do I simulate a click on a div with javascript - javascript

I am looking for a way to be able to rig a shortcut to a youtube controll button. I want to be able to click on the left and right arrow to activate "Previous video" and "Next video" on a playlist. I used to be easily able to do it myself, but they made some changes and since those I can't quite replicate what i used to have working.
I use the Google Chrome Shortkey Plug-in to manage my short cut keys. I make the right key execute a javascript code only on "https://www.youtube.com*"
The problem reside in the script to execute. I used to simply do a document.getElementById but now they use class instead of id and I cant get it to work. Their buttons are divs and they go like this:
<div class="ytp-button ytp-button-prev" role="button" aria-label="Previous" tabindex="6050" style="display: inline-block;">
</div>
<div class="ytp-button ytp-button-next" role="button" aria-label="Next" tabindex="6051" style="display: inline-block;">
My code actualy comes from another Stackoverflow Question
Still, if I put all of that together to make the folowing code it doesn't work.
simulate(document.getElementsByClassName("ytp-button ytp-button-prev"), "click");

getElementsByClassName returns an array, since you can have multiple elements with the same class name. You can pick them by document.getElementsByClassName("ytp-button ytp-button-prev")[index]

jQuery is not the best solution for all our projects, but for simulate events it's not bad option
(function($){
$('.element').click();
// same for others ex: $('.element').keyup();
})(jQuery);
example: http://jsfiddle.net/h0po3q3w/

If you are using jQuery, you can target the element then trigger a click event like this:
$( ".ytp-button-prev" ).trigger( "click" );

Jason has your answer, but an alternative is to use document.querySelector. If there is only one button with those classes, or you want the first one, then:
var button = document.querySelector('.ytp-button.ytp-button-prev');

Related

How to simulate .click() on mobile

I need to click a div to do an action.
I do desktop version succesfully, but when I go to mobile, click action does not work. I try several ways that found here in Stack Overflow and other websites, but any works...
My code for desktop:
document.getElementById('BtMisDocumentos').click();
My code for mobile (3 attempts);
$('BtMisDocumentos').trigger('vclick');
$('BtMisDocumentos').trigger('tap');
$('BtMisDocumentos').trigger('touchstart');
Div;
<div id="BtMisDocumentos" class="dx-button dx-button-normal dx-button-mode-text dx-widget dx-button-has-text" onclick="void(0)" role="button" aria-label="Mis Documentos" style="width: 140px;"><div class="dx-button-content"><span class="dx-button-text">Mis Documentos</span></div></div>
Any idea? maybe does not work, because I am using a user agent, despite of a "real" mobile?
I think you are missing something:
//Use a . for a element class and # for a element id. Use it in the $('#...') part.
$('.BtMisDocumentos').trigger('vclick');
$('#BtMisDocumentos').trigger('tap');
$('.BtMisDocumentos').trigger('touchstart');
Try this with .click() aswell.
jQuery docs:
https://api.jquery.com/click/
EDIT #TWISTY:
If you want to just copy and paste:
//With a HTML class attribute. Example: <div class="BtMisDocumentos"></div>
$('.BtMisDocumentos').trigger('vclick');
$('.BtMisDocumentos').trigger('tap');
$('.BtMisDocumentos').trigger('touchstart');
$('.BtMisDocumentos').click();
//With a HTML id attribute. Example: <div id="BtMisDocumentos"></div>
$('#BtMisDocumentos').trigger('vclick');
$('#BtMisDocumentos').trigger('tap');
$('#BtMisDocumentos').trigger('touchstart');
$('#BtMisDocumentos').click();
When using jQuery versus JavaScript, you will use CSS Style Selectors.
$('#BtMisDocumentos').trigger('vclick');
$('#BtMisDocumentos').trigger('tap');
$('#BtMisDocumentos').trigger('touchstart');
For your code, the following should work still on Mobile:
$('#BtMisDocumentos').click();

jquery to add one cell without refreshing the page

I want to add one cell in a section each time I click the add button. The page is updated without refreshing.
The html code is:
<section>
<p class="cell">content</p>
</section>
<button type="button" id="addCell">add</button>
How should I implement the js?Thanks!
Very simple, use append() or after(). In your case append() will work better.
$('#addCell').bind('click',function(){
$('section').append('<p class="cell">content2</p>');
});
Unfortunately I can't show you a demo because jsFiddle is under maintenance.
Demo in jsbin: http://jsbin.com/agosap/
I won't give you the code as you haven't shown us what you've attempted, but I will guide you.
You want to bind a click event to the button so you can do stuff when the user clicks it. You can create elements using JS document.createElement or using jQuery. So inside the click event, create the element you want, give it whatever attributes you want, and then append it to the parent div.
$(document).ready(function() {
$("#addCell").click(function() {
$("section").append('<p class="cell">content</p>');
});
});

Click a button made from div with JavaScript?

In Google+, the button that is used to post a comment is made from a div:
<div role="button" id=":1vq.post" class="d-s-r tk3N6e-e tk3N6e-e-qc" aria-disabled="false" style="-webkit-user-select: none; " tabindex="0">Post comment</div>
I think I can click it with:
document.getElementById(":1vq.post").click();
But it says that the element have no attribute click, and I found that onclick is null. So how could I click the button with JavaScript?
EDIT: After a chat with wong2 who started this question and a lot of failed guesses for what this question is really about (the question is quite poorly written), what they are trying to do is to write a Greasemonkey userscript to make the enter key press the Post Comment button in Google+ streams. Since I don't have an invite into Google+ yet, I can't even see the relevant code so not much I can do. This question is not about putting anything related to Google+ in your own site - it's about trying to use Greasemonkey to modify the behavior of Google's site in your own browser.
Earlier attempts to help:
id=":1vq.post" is not a legal CSS id name. You can't use the ":" character in a selector name. This causes multiple issues because not only is it not a legal character, but it's also a meaningful character in the CSS selector syntax. So, I see that you have two issues.
First, your selector logic is not working. Second, as others have said, you can't just assign to click in this way with plain javascript (e.g. no framework).
If you change your selector logic to work correctly, you can get it to work properly (using jQuery) like this:
<div role="button" id="aPost" class="d-s-r tk3N6e-e tk3N6e-e-qc" aria-disabled="false" style="-webkit-user-select: none; " tabindex="0">Post comment</div>
$("#aPost").click(function() {
alert("I was clicked.");
});
And, you can see it in action in this jsFiddle: http://jsfiddle.net/jfriend00/Yfnc7/. Click Run and then click on the Post Comment.
click() applies only to elements like input and button.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-2651361
onclick would appear in 1990 and not at Google. They should be using addEventListener.
Try to set a breakpoint and see what function is called on click. Then call the function directly.
To trigger a click event handler one can use createEvent plus dispatchEvent.
See example: http://jsfiddle.net/DzVg9/
Note, that Google Plus may actually be using mousedown or mouseup events.
Are you sure you are acurately selecting the button with $(":1vq.post")? Perhaps you need to change it to $("#:1vq.post") or something like that (I'm not sure how JQuery handles the : and . characters).

Invoking Link in Javascript or jQuery

I have an href taged object (graphic) on a page that I want to programatically click on. However,I can't figure out how to reference the object. Here is the tag:
<div id="getthebutton">
<div>
<a onmouseout="MM_swapImage('btn123','','http://www.comp.com/img/btn_img.png',1)" onmousedown="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" onmouseover="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" href="javascript:do_activity("param1", 1);">
<img id="btn123" width="180" height="60" alt="" src="http://www.comp.com/img/buttons/other_btn.png"/>
</a>
</div>
</div>
How do I click on this thing? If I read this right "btn123" is just an image file.
To programmatically click on that you would have to do something like this
$("a").click();
Of course it helps to have an event handler assigned first, but it is really that simple :)
Using parentNode will give you access to the <a> tag, but I don't know if that helps you, cause I'm not sure what exactly you are doing.
document.getElementById("btn123").parentNode
I believe in jQuery, it is parent():
$('#btn123').parent()
So you could probably do:
$('#btn123').parent().click()
First off, you should really listen to the comments (javascript: links == dark side). That being said ...
$("div#getthebutton div a").click();
In this case, the anchor has a javascript href-value. Understanding that you have no control over the source, your only other option would be to evaluate the value of the HREF:
// run the href-javascript from the parent anchor
eval($("#btn123").parent().attr("href"));
Invoking a click from the code will not invoke the javascript code. As such, you must evaluate it instead.
If you want to get the result of clicking on the image, from the code I would say your JavaScript should simply be:
do_activity("param1", 1);
That's what ultimately happens when the image is clicked by a human. This bypasses the 'click' events, so you might miss out on some side-effects, but it's what I'd try first.

Unobtrusive Javascript: Removing links if Javascript is enabled

I'm using PopBox for magnifying thumbnails on my page.
But I want my website to work even for users which turned javascript off.
I tried to use the following HTML code:
<a href="image.jpg">
<img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/>
</a>
Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work.
How do I do that?
Just put the onclick on the a-tag:
<img ...>
Make sure to return false either at the end of the function (here Pop) or inline like in the above example. This prevents the user from being redirected to the link by the <a>'s default behaviour.
Put the onclick event onto the link itself, and return false from the handler if you don't want the default behavior to be executed (the link to be followed)
You could give all your fallback anchor tags a particular classname, like "simple"
Using prototype, you can get an array of all tags using that class using a CSS selector, e.g.
var anchors=$$('a.simple')
Now you can iterate over that array and clear the href attributes, or install an onclick handler to override the normal behaviour, etc...
(Edited to add that the other methods listed above are much simpler, this just came from a background of doing lots of unobtrusive javascript, where your JS kicks in and goes and augments a functioning HTML page with extra stuff!)
May I suggest, in my opinion, the best solution? This is using jQuery 1.4+.
Here you have a container with all your photos. Notice the added classes.
<div id="photo-container">
<a href="image1.jpg">
<img class="popup-image" src="thumbnail1.jpg" pbsrc="image1.jpg" />
</a>
<a href="image2.jpg">
<img class="popup-image" src="thumbnail2.jpg" pbsrc="image2.jpg" />
</a>
<a href="image3.jpg">
<img class="popup-image" src="thumbnail3.jpg" pbsrc="image3.jpg"/>
</a>
</div>
An then you make a single event handler this way:
<script type="text/javascript">
$(document).ready(function(){
var container = $('#photo-container');
// let's bind our event handler
container.bind('click', function(event){
// thus we find (if any) the image the user has clicked on
var target = $(event.target).closest('img.popup-image');
// If the user has not hit any image, we do not handle the click
if (!target.length) return;
event.preventDefault(); // instead of return false;
// And here you can do what you want to your image
// which you can get from target
Pop(target.get(0));
});
});
</script>
The href attribute is not required for anchors (<a> tags), so get rid of it...
<a id="apic001" href="pic001.png"><img src="tn_pic001.png"></a>
<script type="text/javascript">
document.getElementById("apic001").removeAttribute("href");
</script>
This method will avoid library contention for onclick.
Tested in IE6/FF3/Chrome. Side benefit: You can link directly to the portion of the page containing that thumbnail, using the id as a URI fragment: http://whatever/gallery.html#apic001.
For maximum browser compatibility, add a name="apic001" attribute to the anchor tag in your markup ('name' and 'id' values must be identical).
Using jQuery, dojo, Prototype, etc. you should be able to do the removeAttribute on multiple, similar anchors without needing the id.
You should be able to mix and match the return false from Chris's idea with your own code:
<a href="image.jpg" onclick="return false;">
<img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);">
</a>
If someone has Javascript disabled, then their browser ignores the onclick statement in both elements and follows the link; if they have Javascript enabled, then their browser follows both OnClick statements -- the first one tells them not to follow the <a> link. ^_^

Categories

Resources