Vanilla Javascript find element with attribute on click - javascript

I am trying to translate these few lines of jQuery based code into vanilla JS but I am struggling. Can someone please explain how to do it?
function googletranslate() {
$(".footer-toggle li, .select-lng li").on("click", function() {
var rel = $(this).children("a").attr("rel");
$(".goog-te-menu-frame:first").contents().find(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')").get(0).click();
});
}
setTimeout(googletranslate, 1000);
I know how to do a click event with javascript but im having a hard time finding the element (Just started learning).
Spanish
Basically when the link is clicked, it feeds through rel value to the hidden google translate widget, and simulates a click on the desired language.
Can someone explain how please? Would it be easier to use a select box and get the value from that instead?

document.querySelector('a[rel="Spanish"]')
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

function googletranslate() {
['.footer-toggle li', '.select-lng li'].forEach(selector => {
const elm = document.querySelector(selector);
elm.addEventListener('click', clickHandler);
});
function clickHandler(e) {
const rel = e.target.querySelector('a').getAttribute('rel');
const someGoogleSpan = document.querySelector(".goog-te-menu-frame:first")
.querySelectorAll(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')")[0];
someGoogleSpan.click();
}
}
setTimeout(googletranslate, 1000);

Related

Get .textContent clonned on some div. Show with mouseOver/out function

Good morning community, I would like to know if someone can help me with this problem.
My idea is the following: Each image in the homepage section (8 images), has associated:
<div id="project__caption" class="relative -z-10 hidden">
<p>Your description image here</p>
</div>
Which I pass to clone and store into a new div created as #cursor-outer.
I have done this code to achieve the above explained:
cursorText: function () {
if (!isMobile() || !isTouchDevice()) {
const projectCap = document.querySelectorAll("#project__caption");
const cursorText = document.getElementById("cursor-outer");
for (let i = 0; i < projectCap.length; i++) {
const element = projectCap[i];
const clonned = cursorText.appendChild(element.cloneNode(true));
clonned.classList.add("is-inactive");
}
}
},
Every time I use the mouseOver / mouseOut function I need to get this new and display it only above this image, and then hide it when i move cursor out image.
So i need now to make 2 functions like : mouseOver / mouseOut,
Can anyone help me to get this code transform to vanilla js (actually working with jquery)
function mouseOver() {
var hoveredProject = $(this).find(".project__caption").text();
var hoveredProjectActive = $(
"#cursor-outer .project__caption:contains('" + hoveredProject + "')"
);
$(hoveredProjectActive).filter(function () {
if ($(this).text() === hoveredProject) {
$(this).removeClass("is-inactive").addClass("is-active");
}
});
function mouseOut() {
var hoveredProject = $(this).find(".project__caption").text();
var hoveredProjectActive = $(
".project__caption:contains('" + hoveredProject + "')"
);
hoveredProjectActive.removeClass("is-active").addClass("is-inactive");
}
Thanks to anyone in advance, appreciate any help :)

Adding a class using JavaScript

Could anyone give me a hand with the following JavaScript issue.
I am trying to come up with a function that adds a class to a div that has a specified class.
I have tried to come up with something based on what a few people have said but it doesn't seem to work.
http://jsfiddle.net/samsungbrown/vZ9Hu/
Where am I going wrong?
Thanks
function toggleClass(matchClass,content) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
elems[i].classList.toggle(content);
}
}
}
window.onload = function () {
toggleClass("col-left","display");
}
Because of some quirks in jsFiddle your code doesn't run. Remove the .onload wrapper and your code runs. See: http://jsfiddle.net/vZ9Hu/1/

javascript - trying to make an onClick alert based on id/class

I'm new to programming and was wondering how to make a customized alert that shows the id or class name of the object when I click on it. My site has a picture of 8 different animals, and I want it so that every time I click on one of the animals there's an alert with "This is a (animal's name)". Why won't my javascript code below work?
should i be using "this" instead of "parama"? i don't understand whether or not to have any parameters for my function clicky.
var images = new Array()
images[0] = "bison"
images[1] = "frog"
function clicky(parama){
for (entry in images){
if (parama.attributes["name"].value === images[entry]){
$(parama).onClick(alert("This is a" + parama.attributes["name"].value));
} else {
$(parama).onClick(alert("dang it");
}
}
}
using sort of a combination of both your answers, I figured out a way to do it with a lot less code than I originally had. Check it out! (images all had classes of "pic")
$('.pic').click(function(){
alert("This is a " + this.getAttribute('alt'))
});
I'd recommend to use the title or alt attribute on images instead of a JS array - that's more SEO friendly and semantic. Not to mention that alt is required on images to make your HTML valid - DEMO
var images = document.getElementsByTagName("img");
for ( var i = 0, count = images.length; i < count; i++ ) {
images[i].addEventListener("click", function() {
alert( this.getAttribute("alt") );
});
}
UPDATE
if you open to use jQuery - DEMO
$("img").on("click", function() {
alert( $(this).prop("alt") );
});​
You can use .click() but it's recommended to use .on() instead to attach different kind of event listeners to elements. jQuery also provides a shorthand for getting the properties - .prop()

Javascript - swap image on click or rollover

I know how to do this in jquery but i am trying to do the below in pure old school javascript. Can someone help:
$(".thumbnail").click(function() {
$("#mainImage").attr("src", $(this).attr("src"));
});
My ultimate goal is to click on a thumbnail and have the main image change but I need to do it in javascript (no jquery). I know this sounds pretty simple but I cannot figure it out. thank you.
There are so many things that jQuery gives you automatically that it's difficult to give you an answer that will do everything that your jQuery code does. Here is a simple example that will find every image with a class of thumbnail and set its onclick property to an event handler that performs an image swap.
onload = function () {
var bigImg = document.getElementById("mainImage");
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (/\bthumbnail\b/.test(img.className) {
img.onclick = thumbnailHandler;
}
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
If you don't have to support IE7, you can simplify it slightly by using document.querySelectorAll():
onload = function () {
var bigImg = document.getElementById("mainImage");
var thumbs = document.querySelectorAll(".thumbnail");
for (var i = 0; i < thumbs.length; i++) {
thumbs[i].onclick = thumbnailHandler;
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
As an aside, I don't understand why you are setting the source of the main image to be the source of the thumbnail. Are you loading the full image into the thumbnail? That can be a lot to download and can quickly increase the memory footprint of your page.
Event delegation is probably the easiest way:
function expandThumbnail(e) {
if(~(' ' + e.target.className + ' ').indexOf(' thumbnail ')) {
document.getElementById('mainImage').src = e.target.src;
}
}
if(document.addEventListener) {
document.addEventListener('click', expandThumbnail, false);
} else {
document.attachEvent('onclick', function() {
expandThumbnail({
target: event.srcElement
});
});
}
If I understand right, you have a thumbnail image displayed, let's say '1thumb.png', of an associated image, let's say '1.png', and when you click this thumbnail image you want to change the src attribute of a main image, let's say with id='mainimg', to show the '1.png' image associated to the thumbnail instead of whatever it's showing. I tried this and it works:
Inside your <header>:
<script type='text/javascript'>
function myHandler(source){
document.getElementById('mainimg').src=source;
}
</script>
...
Your thumbnail code:
<img src='1thumb.png' onclick="myHandler('1.png')"/>
or, for rollover triggering:
<img src='1thumb.png' onmouseover="myHandler('1.png')"/>
Check it out: http://jsfiddle.net/d7Q27/7/

I need to set display: block on div then find an anchor within that div

I'm nearly finished with this project but I have been beating my head against this problem for a day or so.
Big picture:
Im trying to create a link that will jump between tabs and find an anchor.
Details:
I need to create a link which triggers the function that hides the current div (using display: none)/shows another div (display: block;) and then goto an anchor on the page.
My first intuition was to do:
code:
<a onClick="return toggleTab(6,6);" href="#{anchor_tab_link_name}">{anchor_tab_link_name}</a>
Since the onClick should return true and then execute the anchor. However it loads but never goes to the anchor.
Here is the toggleTab function to give some context:
function toggleTab(num,numelems, anchor, opennum,animate) {
if ($('tabContent'+num).style.display == 'none'){
for (var i=1;i<=numelems;i++){
if ((opennum == null) || (opennum != i)){
var temph = 'tabHeader'+i;
var h = $(temph);
if (!h){
var h = $('tabHeaderActive');
h.id = temph;
}
var tempc = 'tabContent'+i;
var c = $(tempc);
if(c.style.display != 'none'){
if (animate || typeof animate == 'undefined')
Effect.toggle(tempc,'appear',{duration:0.4, queue:{scope:'menus', limit: 3}});
else
toggleDisp(tempc);
}
}
}
var h = $('tabHeader'+num);
if (h)
h.id = 'tabHeaderActive';
h.blur();
var c = $('tabContent'+num);
c.style.marginTop = '2px';
if (animate || typeof animate == 'undefined'){
Effect.toggle('tabContent'+num,'appear',{duration:0.4, queue:{scope:'menus', position:'end', limit: 3}});
}else{
toggleDisp('tabContent'+num);
}
}
}
So I posted this on a coding forum and a person told me that my tab code was done in prototype.
And that I should "Long story short: don't use onclick. Attach the data to the A tag and handle the click event yourself (using preventDefault() or similar) to do your tab-setting stuff, then when it's done, manually set your location to the hash tag."
I do understand what he is suggesting but I don't know how to implement it because I don't know much about javascript syntax.
If you can provide any hints or suggestions it would be amazing.
Update:
I tried to implement the solution below like this:
The link:
<a id="trap">trap</a>
Then adding the following js to the top of the page:
<script type="javascript">
document.getElementById("trap").click(function() { // bind click event to link
tabToggle(6,6);
var anchor = $(this).attr('href');
//setTimeout(infoSupport.gotoAnchor,600, anchor);
jumpToAnchor();
return false;
});
//Simple jump to anchor point
function jumpToAnchor(){
location.href = location.href+"#trap";
}
//Nice little jQuery scroll to id of any element
function scollToId(id){
window.scrollTo(0,$("#"+id).offset().top);
}
</script>
But unfortunately it simply doesn't seem to work for me. When I click the text simply nothing happens.
Anyone notice any apparent mistakes? I'm not used of working with javascript.
I found a lot simpler solution:
$(function(){
jumpToTarget('spot_to_go'); //This is what you put inside your function when the link is clicked.
function jumpToTarget(target){
var target_offset = $("#"+target).offset();
var target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
}
});
Working demo:
http://jsbin.com/ivure/3/edit
So on the click event you do something like this:
//Untested
$('#trap').click(function(){
tabToggle(6,6);
var anchor = $(this).attr('href');
jumpToTarget(anchor);
return false;
});
​
Apparently a small delay was all I needed.
I used this for the link. This is preferred for my situation since I'm batch generating many of these links.
trap
Then I used this vanilla javascript
//Simple jump to anchor point
function jumpToAnchor(target){
setTimeout("window.location.hash=target",450);
}
This loads the link and instantly goes to the location. No jerkiness or anything.

Categories

Resources