I'm trying to automate a click when visting a website. This is the HTML I'm looking at.
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
when I select the size, say for instance size 8, the class= tag turns to "box active" like so,
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box active">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this,
<div class="add_to_cart">
<div class="add_to_cart_left">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
<img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img>
</div>
</div>
Is this the correct chunk of HTML I should be looking at for a simulation of a click?
Since it's Christmas and you sounded excited to see jQuery in action I created a fiddle for you. Here is a sample of what you (could) want using jQuery: http://jsfiddle.net/akkJ5/2/
The code for selecting sizes and twiddling active classes is as follows:
var selectedSize = '';
$(".box").click(function(){
$(".box").removeClass('active');
$(this).addClass('active');
selectedSize = $(this).html();
$("#messages").html(selectedSize +" was selected");
});
In it I create an event listener for clicks on all box class elements. Since only one should be active I remove the active class from all box class elements then add active to the clicked box. I save the innerHTML of the selected link as selectedSize, and write it to an element for display sake.
In terms of simulating a click on a button you could do something like this:
$(".add_to_cart").click(function(){
alert('cart clicked');
});
$(".add_to_cart").trigger('click');
Updated
To attach event to all the classed you can do
var selectedvalue = '';
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
d.onclick = function (e) {
selectedvalue = this.text;
this.className = this.className + " active";
}
}
Check http://jsfiddle.net/raunakkathuria/Nv8t2/2/
To navigate through classes and add your class to the link that has same value
JS
var value = 8;
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
if(d.text == value) {
d.className = d.className + " active";
}
}
To simulate the click handler for the add to cart you can enclose them to
<a href="javascript:void(0)" onclick="myJsFunc();">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
</a>
If you want to send it some link update this href="javascript:void(0)" onclick="myJsFunc();" to href="your_link"
Check http://jsfiddle.net/raunakkathuria/Nv8t2/1/
Related
An image is display to my webpage, all having the same class name.
I try hiding a particular one with it is clicked but any time I click that particular class, all the classes are affected
I used PHP to echo the image to webpage. I have tried all I could but not working.
<img class="media_image" onclick="hide()" src="media/<?php echo $media?>"/>
<script>
function hide(){
var divs = document.getElementsByClassName("media_image");
for(var i = 0; i <= divs.length; i++){
console.log("Item: ", i);
}
}
</script>
You can change onclick="hide()" to onclick="hide(this)" to pass the element into the function and then the function can be changed to accept it.
function hide (element) {
//do whatever with element
element.style.display = "none";
}
you could add a second special class to every image in the webpage like :
<img class="myimg img-1">
<img class="myimg img-2">
<img class="myimg img-3">
// ect
I made shoppping cart. I am using localstorage. But i have problem with removing products, what is bad ?
function showElems(){
$(".cart1").html("<ul class='cartx'></ul>")
for (var i = 0; i < localStorage.length; i++) {
$(".cartx").append("<li class='" +localStorage.key(i) + "' '>" + localStorage.key(i) + "x" + localStorage.getItem(localStorage.key(i)) +
"<button class='removeitem' data-remove='" + localStorage.key(i) + "'>REMOVE</button></li>");
};
};
showElems();
$(".add").click(function(){
var product = $(this).attr("data-name");
localStorage.setItem( product, 1 ); // dodanie jednej sztuki do koszyka
showElems();
});
/* NOT WORKING */
$(".removeitem").click(function(){
var productremove = $(this).attr("data-remove");
localStorage['kubek'] = null;
});
http://codepen.io/dominikx96/pen/rLgjrA
There are several parts of the cart that need a little tweaking. Ultimately though, you're on the right track.
I've cleaned up the code a bit and posted the results down below along with a live working example on jsfiddle.net. An explanation follows the code example to explain the changes:
<!-- CART -->
<section id="cart">
<div class="container">
<div class="cart1"></div>
</div>
</section>
<!-- CATEGORY -->
<section id="koszulki" class="category">
<div class="container">
<h1 class="category-title">KOSZULKI</h1>
<div class="category-content">
<div class="category-item">
<button class="add" data-name="piersiowka">Dodaj do koszyka</button>
<button class="more">Zobacz opis</button>
</div>
<div class="category-item">
<button class="add" data-name="szalik">Dodaj do koszyka</button>
<button class="more">Zobacz opis</button>
</div>
<div class="category-item">
<button class="add" data-name="kubek">Dodaj do koszyka</button>
<button class="more">Zobacz opis</button>
</div>
</div>
</div>
</section>
function showElems() {
var $ul = $('<ul />', { "class": "cartx" });
for (var a = 0, len = localStorage.length; a < len; a++) {
var $li = $('<li />', { "class": localStorage.key(a), text: localStorage.key(a) + "x" + localStorage.getItem(localStorage.key(a)) });
$('<button />', { "class": "removeitem", data: { remove: localStorage.key(a) }, text: "REMOVE" })
.appendTo($li);
$li.appendTo($ul);
}
$ul.appendTo($('.cart1').empty());
};
showElems();
$("#koszulki").on('click', '.add', function() {
if(!localStorage.getItem($(this).data('name'))) {
localStorage.setItem($(this).data('name'), 1 );
showElems();
}
});
$("#cart").on('click', '.removeitem', function() {
localStorage.removeItem($(this).data('remove'));
showElems();
});
DEMO: https://jsfiddle.net/5jmmzgkh/2/
The first change that was made was in the showElems() function. The unordered list is now being created in memory and then appended to the .cart1 element. This change is meant to reduce the number of CSS reflows that happen by preventing the browser from redrawing the UI after each list element is appended. It's a subtle change and you won't notice a difference in the three items that are appended. However, if the list were to grow to a few thousand items, the performance gain would become apparent.
The second change that is the delegation of both click events for .add and .removeitem. Not only is the delegation of these events more performant, but it is also required with the .removeitem elements since those elements are not on the screen when the event handler is created. Without delegation here, this handler would not work which is what I would guess is your problem as you note that that handler is not working in your question.
Third, I tweaked your click handler for the .add elements to prevent adding of the same element to your cart. Depending on your use case, you may want to increment the quantity as oppose to only allow the user to add one of each item to the cart. In this case, you'll want to see if the item is already in the user's cart and: if so, increment the quantity value, or if not add the item to the cart.
Finally, I updated the .removeitem function to not only remove the item from the user's cart but to also update the cart UI so that the element disappears from the cart display.
This is the code of a button in one html page
<a class="btn" role="button" href="#">Click me</a>
I have this javascript code to click a button with a certain class
var clickBtn = document.getElementsByClassName('btn');
for(var i=0;i<clickBtn.length;i++)
{
clickBtn[i].click();
}
This code clicks every button with the class "btn" in ALL the page.
But there are some other buttons in the same page with the same class.
So i want my javascript code to be modifided to click
only a certain button in a certain div.
The code with the div is
<div class="inside">
<span>
<a class="btn" role="button" href="#">Click me</a>
</span>
</div>
Any idea of how can i modify my javascript code to click only the button inside that div??
Thanks for your time.
You can use querySelectorAll()
Array.from(document.querySelectorAll('.inside .btn')).forEach(btn => {
alert(btn.innerHTML)
btn.click();
});
Or without es6:
[].slice.call(document.querySelectorAll('.inside .btn')).forEach(function(btn) {
alert(btn.innerHTML)
btn.click();
});
DEMO
Updated for your comment (Can you update your code that if there is an id in the span like not to click the button?):
[].slice.call(document.querySelectorAll('.inside .btn')).forEach(function(btn) {
if (btn.parentNode.id != 'clicked') {
alert(btn.innerHTML);
btn.click();
}
});
or you can use querySelectorAll() with a :not condition to avoid the if check:
Array.from(document.querySelectorAll('.inside span:not([id="clicked"]) .btn'))
.forEach(btn => {
alert(btn.innerHTML)
btn.click();
});
If you want a non-jQuery solution, you can use getElementById to get the div, and then getElementsByClassName to get all the buttons within that div.
var insideDiv = document.getElementById("inside");
var buttonsInsideDiv = insideDiv.getElementsByClassName();
var parentDiv = clickBtn[i].parentNode;
var clickBtn = document.getElementsByClassName('btn');
for(var i=0;i<clickBtn.length;i++)
{
var parentDiv = clickBtn[i].parentNode;
if(parentDiv == yourDiv)
{
clickBtn[i].click();
}
}
I am not sure, var parentDiv = clickBtn[i].parentNode will work. But the idea is the same.
I've been trying to solve this for the last couple of hours but all attempts failed...
What I need to do is to click on a DIV that will cause another DIV to pop up.
Inside the pop up there are some <li> and after clicking it, the attribute name is "transferred" to the first DIV clicked.
Ok, I managed to do that but after I update the first DIV and when I try to update the second DIV, the first DIV also gets updated and when I try to update the third DIV the other two gets updated ass well.
Can anyone help me to fix it and only update the DIV it was clicked on leaving the previous as it was supposed to be?
Here is the code:
HTML
<div class="num-1">
<img src="http://dummyimage.com/180x180/eeeeee/000000.jpg" width="180" height="180">
<p class="brand"></p>
<p class="name"></p>
</div>
<div class="num-2">
<img src="http://dummyimage.com/180x180/eeeeee/000000.jpg" width="180" height="180">
<p class="brand"></p>
<p class="name"></p>
</div>
<div class="num-3">
<img src="http://dummyimage.com/180x180/eeeeee/000000.jpg" width="180" height="180">
<p class="brand"></p>
<p class="name"></p>
</div>
<div class="num-4">
<img src="http://dummyimage.com/180x180/eeeeee/000000.jpg" width="180" height="180">
<p class="brand"></p>
<p class="name"></p>
</div>
<div class="num-5">
<img src="http://dummyimage.com/180x180/eeeeee/000000.jpg" width="180" height="180">
<p class="brand"></p>
<p class="name"></p>
</div>
<div class="popup">
<ul>
<li name="{{PHP GENERATED $name}}">{{PHP GENERATED $name}}</li>
<li name="{{PHP GENERATED $name}}">{{PHP GENERATED $name}}</li>
<li name="{{PHP GENERATED $name}}">{{PHP GENERATED $name}}</li>
</ul>
</div>
jQuery
//Openning the .popup and assigning the names
//First check the number of the div it was clicked on
$('img').on('click', function() {
var num = $(this).parent().attr('class').match(/\d+/)[0];
$('.popup').fadeIn();
//Click li to update the brand and name on the page
$('.popup li').on('click', function() {
//Check the name and split it
var nameComplete = $(this).attr('name');
var Array = nameComplete.split(" ");
//Check the first word and identify it as brand, also update on the page
var brand = Array[0];
$('.num-' + num + ' .brand').text(brand);
//Check the rest of the array for the name and update it on the page
var name = '';
for(var i=1; i<Array.length ;i++) {
name = name + Array[i] + ' ';
}
name = $.trim(name);
$('.num-' + num + ' .name').text(name);
$('.popup').fadeOut();
});
});
Someone might wonder if I'm getting the number of the DIV correctly.
I did console.log(num); and it shows that I'm clicking on the correct DIV because the DIV class is num-X (X = 1 to 5), 1 for 1, 2 for 2,...
The names of the <li> are ok, it works as it should, split it and get the right part to "transfer".
I guess I made the proper modifications to better understanding the code.
$('img').on('click', function() {
var num = $(this).parent().attr('class').match(/\d+/)[0];
window.num = num;
$('.popup').fadeIn();
});
//Click li to update the brand and name on the page
$('.popup li').on('click', function() {
//Check the name and split it
var nameComplete = $(this).attr('name');
var Array = nameComplete.split(" ");
//Check the first word and identify it as brand, also update on the page
var brand = Array[0];
$('.num-' + window.num + ' .brand').text(brand);
//Check the rest of the array for the name and update it on the page
var name = '';
for(var i=1; i<Array.length ;i++) {
name = name + Array[i] + ' ';
}
name = $.trim(name);
$('.num-' + num + ' .name').text(name);
$('.popup').fadeOut();
});
Separate both the click events in separate functions. Probably whats happening in your code is that every time you click on a div a new click event handler is attached to the '.popup li' and every time you click on one of the '.popup li' all the click handlers are activated. Thus explaining the multiple divs being updated.
Second option you have is to use jquery.off. This way every time you attach an event handle with .click to the '.popup li' you also remove it after you work is done and complete. Since this would have made your code harder to debug and to read i have preferred the first method in this answer.
NOTE**- i have changed the num to window.num which isnt a very good practice (keeping a global variable) but im sure you will be able to refactor the code once you get it to work
I'm aware that this issue was addressed many times, that's why I read most of the topics on this problem that were already opened on Stack Overflow but none of the suggestions have helped me.
I have a list of div elements, each containing a hyperlink and a span element with additional information. The span elements are initially hidden and they need to be toggled whenever the sibling anchor element is clicked.
<div class="politician">
<a href="">
Антонијо Милошоски
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1997-1
</span>
</div>
<div class="politician">
<a href="">
Силвана Бонева
</a>
<span class="additional" style="display: none">
2013ВМРО-ДПМНЕ1991-1
</span>
</div>
Here's the jQuery code I have written to handle the toggling of the hidden elements:
$('.politician a').click(function (e) {
e.preventDefault();
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$this.toggle();
});
My problem was already stated in the title. I'm expecting the hidden elements to be shown, but instead the page gets refreshed. I guess there has to be something wrong with the way I'm using the preventDefault() method.
EDIT
Here is the piece of code that generates the div.politician elements.
function populateList(politicians) {
var politlist = $("#list").html("");
for (var i in politicians) {
var person = politicians[i];
var politinfo = "<div class=\"politician\">" + person.name + " " + person.surname + "<span class=\"additional\" style=\"display: none\">" + person.lastserved;
for (var j in person.member)
{
var membership = person.member[j]
politinfo += membership.party + membership.enrol + membership.leave;
}
politinfo += "</span></div>";
$(politinfo).appendTo(politlist);
}
}
Since you're adding elements dynamically, you need to use event delegation:
$('#list').on('click', '.politician a', function(e) {
// your code
});
This is happending because your html is not loaded when you add click event listener to it.
Wrap your code in document.ready function, like this:
$(function(){
$('.politician a').click(function (e) {
var $this = $(this).parent().find('span');
$(".politician span").not($this).hide();
$(this).toggle();
e.preventDefault();
});
});
http://plnkr.co/edit/gist:1986619?p=preview