From JQuery to Javascript code - javascript

I have this div
<div id="lk_37" class="lk_link" style="display: inline-block">
TADE
</div>
And i want to make one script to check if the button_37 is clicked
and if is clicked to go on, if its unclicked then the script should click it.
Also we have a page with different id's of buttons and we want to check them all and click what is unclicked with this particular button.
when the button is clicked the "TADE" is turning on "DTT" this is what i want to check if its clicked or unclicked. we click "TADE" with this class="lk_button_37 lk_post" and its turning on to "DTT" with the same class="lk_button_37 lk_post" as before. so we want to check if "TADE" is on we want the button to be clicked, and if "DTT" is on we want to override it.
The JQuery code for doing this is
$('.lk_button_37:contains(TADE)').click();
And i want to convert this to javascript code for chrome extension.
I've already made up this
var el = document.getElementsByClassName('lk_button_37');
for (var i=0;i<el.length; i++)
{
el[i].click();
}
But i dont know how to make the code click ONLY the "TADE" button.
Any help would be appreciated. Thanks!

Just check the content of the element
var el = document.getElementsByClassName('lk_button_37');
for (var i=0;i<el.length; i++) {
if ( el[i].innerHTML.indexOf('TADE') != -1 ) {
el[i].click();
}
}

Related

Loop through gallery images as links not console logging onclick, but becoming active via css

I am trying to loop through a gallery of gradient swathes, to highlight them so they can be edited back in the main image, but hitting a roadblock when clicking them to test they are working. They are in a bootstrap row, as col-md-3's, and each swatch bg has an id of bg-gradient (row id is gallery). The below code works in as much as they become active via the css when hovered, but wont console log a test message on click.
html structure is a bootstrap row with id of "gallery", then 4 col-md-3's with id of "swatch", then the actual bg-gradient is what is being looped through. These become active on hover via css settings not via the JavaScript, but wont console log test message on click.
Demo
Code:
editSwatch() {
let swatchs = document.querySelectorAll('swatch'),
//let swatchs = document.getElementById('gallery'),
links = swatchs.getElementsByTagName('bg-gradient'),
i;
for (i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function () { console.log('click works') });
}
Updated code as per comments below, but still exactly the same result, tried tagName on the links var and still same.
Seems to be finding the swatches, but not working on click.
Need to get that click working to carry on?
Any tips welcome.
Thanks.
You can not keep same id for swatchs, also you can use below query selector with appropriate selector as parameter and loop through swatchs
var swatchs= document.querySelectorAll(".swatchs");
Technically onclick needs to be a function instead. Currently you are passing the return value of console.log() which is undefined I believe. A function needs to be attached to click event in order to make it work.
You can use addEventListener as the following:
links[i].addEventListener('click', function () { console.log('click works') });
Please see a working example how to attach a click event to a <div>:
const div = document.getElementById('elem');
div.addEventListener('click', function () { console.log('hey hello'); });
<div id="elem">Click me!</div>
I hope this helps!

Toggle script: change from jQuery to "normal javascript" code

I've been using a toggle script (open/close text container when clicking on a certain link) for a website that uses jQuery. In order to clean up the website I want to get rid of jQuery completely but have some problems converting the existing jQuery code into "normal javascript".
Here is the existing code:
jQuery(function($){
$(document).ready(function(){
$(".toggle_container").hide();
$("h4.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("normal");
return false; //Prevent the browser jump to the link anchor
});
});
});
Which corresponds to this HTML source code:
<h4 class="trigger toggle-transparent ">Click to show more</h3><div class="toggle_container ">
Hidden Text
</div>
I've tried the following code which doesn't give me an error but just doesn't do anything when clicking on the trigger:
var el = document.querySelectorAll('h4.trigger');
for(var i=0; i < el.length; i++){
el[i].addEventListener('click', function () {
this.classList.toggle("active").nextSibling.classList.toggle("toggle_container-active");
}.bind(this));
}
The only thing I really need for the code is: clicking on the class "trigger" should toggle some HTML class "active" to both the trigger element as well as the toggle_container element. The rest I'm able to change with just CSS.
The hard part of the code is that it should work for multiple toggle areas on one page separately (therefore using a class, not an id).
Any idea where my code has a problem or any (completely) different suggestions?
I have very limited experience with javascript/jQuery and feel more at home with HTML/CSS.
Thanks,
Patrick
The this.classList.toggle("active") doesn't return the element back again, but just a boolean to inform if the action was successful. Chaining happens only in jQuery and not in vanilla JavaScript.
this.classList.toggle("active").nextSibling.classList.toggle("toggle_container-active");
You should be using something like this instead of the above:
this.classList.toggle("active");
this.nextSibling.classList.toggle("toggle_container-active");

How to store JS slideToggle in localStorage only for clicked button

I have several buttons including divs which they have the same name. unfortunately I can not change the names, they are generated by cms.
So for example when I click only on first button, only the first div is hidden or displayed, and that's fine.
But after refresh page it opens or closes all divs depending is the first div closed or opened, and that I do not want it.
here is the code:
<button class="a">Button</button>
<div class="target"></div>
<button class="a">Button</button>
<div class="target"></div>
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible', $(this).is(":visible"));
});
});
$('.target').toggle(localStorage.getItem('visible') === 'true');
here you can see jsfiddle example: https://jsfiddle.net/pj3gs0z9/3/
So my question is, is it possible to store only clicked button information, and after page refresh display or hide div from only clicked button ?
Thank you
It is possible, but probably not in your case. If you tell us you can't change your button properties, and they are exactly the same, then you won't be able to store different data in your localStorage.
Isn't there any way where you can add some additional information to your button ? It could be a class, an id, a name, or even a data-XXX attribute.
By the way, how are your buttons generated ? are they hard coded, or fetched from a database, or ... ?
EDIT
Here is a way of adding different classes to all of your buttons (althoguh I recommend adding data attributes, but whatever floats your boat) :
let buttons = document.getElementsByTagName('button'); // Array of your buttons
let index = 0;
for (let button of buttons) {
button.className += 'myCustomClass-' + ++index; // Add a custom class to your buttons
}
// Now in your local storage, you can store the class of the button !
EDIT 2 I would store it like this :
// On click, in VanillaJS (sorry, haven't used JQuery in a while)
button.onclick = () => {
let visibleButtons = localStorage.getItem('visible-buttons') || [];
visibleButtons.push(button.className.match(/(myCustomClass-[0-9]*)/)[0]);
}
This is one quick solution, but because of a slideToggle you gonna have a small flash of milliseconds of a visible div unless you first have them hidden and then based on localStorage display them.
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible-' + $(this).index(), $(this).is(":visible"));
});
});
$.each($('.target'), function(k, trg) {
$(trg).toggle(localStorage.getItem('visible-' + $(trg).index()) === 'true');
});

If all overlays closed, then execute function

I have a button on a banner at the top of my page that launches several yui2 overlays on to the screen. Each overlay has a close button on it (which just changes the visibility to hidden so it can be reused). After the overlays are launched, there is also a button on the banner that appears will close all overlays if clicked.
This gives the use the option to close all or close each one individually. This is what i am stuck on:
If the user closes an individual overlay, after I close the overlay, I want to check if any other overlay is still open. If they happen to have closed all of them individually, then I need to revert the banner at the top and remove the "close all button".
I can search for all overlays by doing a:
var elements = YAHOO.util.Dom.getElementsByClassName('test');
I cant think of the logic I would need to do to go through that array each time they close an overlay to see all of them are set to visibility if hidden. If so, then execute a function. If there is still any overlays visible on the page, then do nothing.
This is the answer I came up with. Just not sure if it is correct.
var elements = document.getElementsByClassName('test');
var visiblecounter = 0;
for (var i = 0; i < elements.length; i++) {
if(elements[i].style.visibility!='hidden'){
alert("not hidden");
visiblecounter ++;
}
}
​
if(visiblecounter > 0){
alert("all overlays are closed individually. you can remove close all button");
}
You mention you are reusing those overlays so since you are pooling the overlays for reuse, I assume you have them in an array or something like that. Instead of checking the DOM (which is always expensive) to see if they are visible or not, loop through the array of overlays checking the visible attribute, like:
var anyVisible = false;
for (i = 0; i < myOverlays.length; i+=1) {
anyVisible |= myOverlays[i].cfg.getProperty("visible");
}
If any of them are visible, disable the button.
I am not sure I get the question, but I will try my best to help. Here are some things I would do. I also define an active class, so my HTML elements would be written as this:
<div class="john active"></div>
and in my css I would write.
.john {display: none};
.active {display: block};
So by default the object is hidden! But when you append the "active" class to it, it appears on the screen. So now we can do the following wizardry.
$(".hideButton").click(function() {
$(this).removeClass("active");
});
If I want to hide all the other objects, assuming that they have the same parent in the DOM
$(".hideOthersButton").click(function() {
$(this).siblings().removeClass("active");
});
if I want to hide all objects that share the same parent.
$(".hideEverything").click(function() {
$(".parent").children().removeClass("active");
});
I hope this helps! let me know if you need more help. The solution uses Jquery but you can repurpose the logic for anything else.

jQuery - Changing Styles and Displaying Certain Elements

Well it seems I know enough Javascript to hurt myself so I come asking help from you guys here. Here is what I am attempting to do and my issue.
I have two forms and only one will be filled out depending on the users choice. They will click one button or the other. When they click the button the form fades in and the button changes classes (goes from a light button to a dark button) Here is were I am running into issues. First I cannot get the form to fade in at all and the buttons will only change classes if I click them twice not once.
One other thing I am not sure how to go about is if I have say form 1 chosen but I meant to click form 2 then I want form one to fade out, form 2 to fade in and the buttons change accordingly. Here is my Code:
JS
<script type="text/javascript">
var $j = jQuery.noConflict();
var $jtest1 = $j('#test1');
var $jtest2 = $j('#test2');
$j("#button1").live('click',function(){
//Fade out form if shown and fade in form selected
$jtest2.fadeOut("slow", function(){
$jtest1.fadeIn("slow");
});
$j('#button1').live('click', function(){
//change class from light to dark
$j(this).addClass('dark_button').removeClass('light_button');
}); //I need to change this class to light if
// button 2 is selected and change button 2 to dark
});
</script>
HTML
<p class="light_button" id="button1">Test 1 </p>
<p class="light_button" id="button2">Test 2 </p>
<div class="hide" id="test1"><p>TEST</p></div>
<div class="hide" id="test2"><p>TEST 2</p></div>
Note: class="hide" is style="display:none"
Thanks for any help because I am a but stuck and not sure to go about this. Also please give me an example because I do not always follow when someone say change this to that etc.
Look at the code below, added comments on why
$j("#button1").live('click',function(){
//Fade out form if shown and fade in form selected
$jtest2.fadeOut("slow", function(){
$jtest1.fadeIn("slow");
});
//The following is inside the click so I do not get added until the first click
//and added after every click so I multiply!
//Hence why it takes 2 clicks
$j('#button1').live('click', function(){
//change class from light to dark
$j(this).addClass('dark_button').removeClass('light_button');
}); //I need to change this class to light if
// button 2 is selected and change button 2 to dark
});
You should be doing something like this
$j("#button1, #button2").live('click',
function(){
//figure out what button was clicked.
if(this.id === "button1"){
var btnA = $j(this);
var btnB = $j("#button2");
var divA = $j('#test1');
var divB = $j('#test2');
}
else{
btnA = $j(this);
btnB = $j("#button1");
divA = $j('#test2');
divB = $j('#test1');
}
//make sure it is not already active, no use to show/hide when it is already set
if(btnA.hasClass('dark_button')){
return;
}
//see if div is visible, if so hide, than show first div
if(divB.is(":visible")){
divB.fadeOut("slow", function(){
divA.fadeIn("slow");
});
}
else{//if already hidden, just show the first div
divA.fadeIn("slow");
}
//Add and remove classes to the buttons to switch state
btnA.addClass('dark_button').removeClass('light_button');
btnB.removeClass('dark_button').addClass('light_button');
}
);
jsfiddle example

Categories

Resources