Loop through element and change based on link attribute - javascript

Trying to figure this out. I am inexperienced at jQuery, and not understanding how to loop through elements and match one.
I have 3 divs:
<div class="first-image">
<img src="images/first.png">
</div>
<div class="second-image">
<img src="images/second.png">
</div>
<div class="third-image">
<img src="images/third.png">
</div>
And off to the side, links in a div named 'copy' with rel = first-image, etc.:
...
Clicking the link will fade up the image in the associated div (using GSAP TweenMax)
Here is the function I've been working on to do this... but I am not fully understanding how to loop through all the "rel" elements, and make a match to the one that has been clicked on.
<script>
//pause slideshow on members to ledger when text is clicked, and show associated image
$(function() {
$('.copy').on('click','a',function(e) {
e.preventDefault();
var slideName = $(this).attr('rel');
$("rel").each(function(i){
if (this.rel == slideName) {
console.log(this);
}
});
//var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
//autoAlpha:1
//});
});
});
</script>
What am I doing wrong? I don't even get an error in my browser. :-(
Thanks to the answer below, I got farther. Here is my revised code.
$('[rel]').each(function(k, v){
if (v == slideName) {
var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
autoAlpha:1
});
} else {
var change_screens_tween = TweenMax.to('.'+slideName+'', 1, {
autoAlpha:0
});
}
});
});
This is starting to work, but makes the screenshots appear and then instantly fade out. And it only works once. Any thoughts?

Add brackets around rel, like so:
$('[rel]').each(function() {
if ($(this).attr('rel') == slideName) {
console.log(this);
}
});

Related

Using an attribute value to add custom links for each images in my wordpres gallery

I'm using Elementor Pro for my photography website and i want to set custom links for each image in the gallery. By default, i can only set a global link which is the same for each image so that's not great.
In fact, i want to set a custom link which will redirect the user to the shop page of the specific image.
I found some code online (thanks to elementhow !) and it's really close to what i want, but i still need to change some things. The thing is a have to manually write all the links in an array and it's not convenient (close to 100 files and growing, if i change the order, i have to reorder the links, etc).
Here's the code i currently use :
<style>.e-gallery-item{cursor: pointer;} </style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('.e-gallery-item');
//Edit the links HERE
var links = [
'https://www.mywebsiteurl.com/product/product-name1/',
'https://www.mywebsiteurl.com/product/product-name2/',
'https://www.mywebsiteurl.com/product/product-name3/',
'https://www.mywebsiteurl.com/product/product-name4/',
];
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});
</script>
I would like to use an attribute value in the algorithm to generate the link automatically for each image. I have the process in my mind, but i don't know how to code this...
Here's the code of one image ,i can set what value i want in "alt".
<div class="e-gallery-image elementor-gallery-item__image e-gallery-image-loaded" data-thumbnail="......" data-width="1024" data-height="768" alt="product-name";"></div>
I would like to use the "alt" attribute to create a unique url for each file, with this format :
'https://www......com/product/product-name/'
"product-name' will take the value of the "alt" attribute of each image.
I tried to change this part of the code (replace "links[i]" by trying to get the attribute value using filteredImages[i].getAttributes) but without success...
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
Can someone give me some tips about how to do that ? I spend 2 years without coding so i'm a bit rusty...
I think this does what you'd like it to, as you have already done you can cycle through each image link using a class.
You can get the value of alt using the .attr() function and then replace the href value of the link.
DEMO
// Cycle through each image using common class
$(".e-gallery-image").each( function() {
// Get value of 'alt' for clicked item
alt = $(this).attr("alt");
// Update href value
$(this).attr("href", "https://www.mywebsiteurl.com/product/" + alt );
});
// Prove that its worked
$(".e-gallery-image").click( function() {
// Confirm all is correct
console.log($(this).attr("href"));
// Assign url to window
location.href = $(this).attr("href");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="e-gallery-image" href="test.com" alt="product1">Product 1</div>
<div class="e-gallery-image" href="test.com" alt="product2">Product 2</div>
<div class="e-gallery-image" href="test.com" alt="product3">Product 3</div>
<div class="e-gallery-image" href="test.com" alt="product4">Product 4</div>
<div class="e-gallery-image" href="test.com" alt="product5">Product 5</div>
In fact it was really simple. I tried to target a parent element and it worked ! If anyone is interested, here's the code i use :
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('YOUR_SELECTOR');
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function() {
location = "YOUR_WEBSITE_URL" + filteredImages[i].querySelector("YOUR_SELECTOR").getAttribute("alt");
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});

How to add translate="no" via JS to a dynamic translation script?

I have a script on my website that translates the text contained within a span when the user mouses over an anchor, and it works just fine. However, browsers that do auto-translation seem to be grabbing the titles that get generated onmouseover and translating them as well, which defeats the purpose of the script. I have tried adding the property translate="no" to the generated text using JS (as seen below in Line 10) but I must be missing something, because it doesn't seem to be having an effect.
Please help?
JS:
$.each($("li"), function(i, elements) {
var links = elements.getElementsByTagName("a");
var article_title = elements.getElementsByClassName("article-title")[0];
$.each(links, function(j, link) {
var previous_title = article_title.innerHTML;
if (!$(link).is('.newspaper, .doi')) {
link.addEventListener("mouseover", function() {
$(article_title).fadeTo(150, 0.5, function() {
article_title.innerHTML = link.title;
$(article_title).prop('translate', 'no');
$(article_title).fadeTo(150, 1, function() {});
});
});
link.addEventListener("mouseout", function() {
$(article_title).fadeTo(150, 0.5, function() {
article_title.innerHTML = previous_title;
$(article_title).fadeTo(150, 1, function() {});
});
});
}
});
});
});
HTML:
<li>
[EN]
[ES]
<span class="article-title">This is an example</span>
</li>
First, are you sure that the script interprets
translate="no"
Property correctly? As in, it figures that this should not be translated? Maybe the code logic appears to be the culprit.
Second, try using .attr instead of .prop?

Moving between 4 buttons and have roll overs stay clicked between

I have seen a few things close to what I want but am not sure how to implement to what I'm doing.
The below code all works fine but have now been asked to make the hover stay in place when each button is clicked. How would I go about this? Or is it better to start again using buttons and not divs?
Here is a jsfiddle (not sure why all the divs are showing here, live only the first one does which is correct)
Example of button:
<div id="tab1" class="tab" style="height:50px; width:160px; background-color:#CCC; float:left;">
<img src=".../images/landing/terms-coach.jpg" onmouseover="this.src='.../images/landing/terms-coach-col-2.jpg'" onmouseout="this.src='.../images/landing/terms-coach.jpg'" />
</div>
https://jsfiddle.net/uqxdum1o/
I've modified the markup and JS a bit to get there but I think this code should fulfil the tab requirement and remove some of the inline JS.
Essentially, store the active image src in an attribute for each tab button:
<div id="tab1" class="tab" style="..."
data-image-active="./images/button1-active.jpg"
data-image="./images/button1.jpg">
<img src="./images/button1.jpg" />
</div>
Then use this to set active state in your javascript for each tab button. I've moved your current code for click handling into this each loop too.
$(document).ready(function(){
var $contents = $('.tab-content');
$contents.slice(1).hide();
$('.tab').each(function() {
$(this).hover(function() {
setButtonActive($(this));
}, function() {
if (!$(this).hasClass('active')) {
setButtonInactive($(this));
}
});
$(this).click(function() {
resetAllButtons();
setButtonActive($(this));
$(this).addClass('active');
var $target = $('#' + this.id + 'show').show();
$contents.not($target).hide();
})
});
});
function setButtonActive(button) {
var img = button.find('img'),
imgSrc = button.attr('data-image-active');
img.attr('src', imgSrc);
}
function setButtonInactive(button) {
var img = button.find('img'),
imgSrc = button.attr('data-image');
img.attr('src', imgSrc);
}
function resetAllButtons() {
$('.tab').removeClass('active').each(function() {
setButtonInactive($(this));
});
}

jQuery slider click event

I am trying to create a click event for the pager anchor on my website and I am having trouble with it not doing the event. Can someone help me figure out where I am going wrong.
Here is my jQuery Code.
<script type="text/javascript">
$('.prodSlider').cycle({
fx: 'scrollLeft',
timeout: 0,
pause: 1,
pager: '.prodPager',
pagerAnchorBuilder: function(idx, slide){
return '' + slide.alt + '';
}
});
$('.prodPager a').on('click', function(){
setCounter(function(idx, slide){
return slide.alt;});
});
</script>
Here is the other JavaScript code
// Create Global Variable
var count = 0;
function setCounter(str){
if(str.indexOf("Sliding") > -1)
{
count = 0;
}
else if(str.indexOf("Swinging") > -1)
{
count = 9;
}
else{
count = 18;
}
}
function getCounter(){
return count;
}
Now all these should be updated when the pager anchor is clicked.
<li>Overview</li>
<li>Features</li>
<li>Options</li>
<li>Finishes</li>
<li>Operators</li>
<li>Drawings</li>
<li>Installation Instructions</li>
<li>CSI Specifications</li>
<li>Request a Quote</li>
This is my sliders id and images.
<div class="prodSlider">
<img src="images.jpg" alt="Sliding"/>
<img src="images.jpg" alt="Swinging Low"/>
<img src="images.jpg" alt="Vertical"/>
</div>
<div class="prodPager" onclick="setCounter(This needs to call the function to get the slides alt values)">
</div>
What should happen is when the pager is clicked it will take the slides.alt text and use that to determine the count. When the count is set it should be grabbed by the links to display the apporiate index of the XML objects. I know the XML is correct because when I hardcode the number in there it works correctly so the problem lies in my JavaScript. I feel that I am incorrectly using the .on('click', function()) and it also may have to do with the scope of my JavaScript variable but I am not sure.
OK the answer what to add this to the .cycle jquery
onPagerEvent: function(idx, slide){
setCounter(slide.alt)
},
and to get rid of the onclick for the prodPager div
http://jsfiddle.net/manish1706/zhzgmq77/
$(document).ready(function() {
alert("hello");
$(".js-header-swipe-image").swipe({
tap: function(event, target) {
alert('tap');
},
swipe:function(event, direction, distance, duration, fingerCount){
//Handling swipe direction.
alert('swipe');
}
});
});
I wonder if you could use the onclick event vs .on('click' - http://www.w3schools.com/jsref/event_onclick.asp

How to detect mouseleave() on two elements at once?

Answer can be in vanilla js or jQuery. I want to hide a div with the id "myDiv" if the user is no longer hovering over a link with the id "myLink" or a span with the id "mySpan". If the user has his mouse over either element "myDiv" will still show, but the second the user is not hover over either of the two (doesn't matter which element the user's mouse leaves first) "myDiv" will disappear from the face of existence.
In other words this is how I detect mouse leave on one element:
$('#someElement').mouseleave(function() {
// do something
});
but how to say (in a way that will actually work):
$('#someElement').mouseleave() || $('#someOtherElement').mouseleave()) {
// do something
});
How to detect this?
Something like this should work:
var count = 0;
$('#myLink, #mySpan').mouseenter(function(){
count++;
$('#myDiv').show();
}).mouseleave(function(){
count--;
if (!count) {
$('#myDiv').hide();
}
});
jsfiddle
You could use a multiple selector:
$("#someElement, #someOtherElement").mouseleave(function() {
// Do something.
});
You can beautifully use setTimeout() to give the mouseleave() function some "tolerance", that means if you leave the divs but re-enter one of them within a given period of time, it does not trigger the hide() function.
Here is the code (added to lonesomeday's answer):
var count = 0;
var tolerance = 500;
$('#d1, #d2').mouseenter(function(){
count++;
$('#d3').show();
}).mouseleave(function(){
count--;
setTimeout(function () {
if (!count) {
$('#d3').hide();
}
}, tolerance);
});
http://jsfiddle.net/pFTfm/195/
I think, it's your solution!!!
$(document).ready(function() {
var someOtherElement = "";
$("#someElement").hover(function(){
var someOtherElement = $(this).attr("href");
$(someOtherElement).show();
});
$("#someElement").mouseleave(function(){
var someOtherElement= $(this).attr("href");
$(someOtherElement).mouseenter(function(){
$(someOtherElement).show();
});
$(someOtherElement).mouseleave(function(){
$(someOtherElement).hide();
});
});
});
----
html
----
<div id="someElement">
<ul>
<li>element1</li>
<li>element2</li>
</ul>
</div>
<div id="tab1" style="display: none"> TAB1 </div>
<div id="tab2" style="display: none"> TAB1 </div>
While the answer from lonesomeday is perfectly valid I changed my html to have both elements in one container. I originally wanted to avoid this hence I had to do more refactoring for my clients in other html templates, but I think it will pay out on the long term.
<div id="my-container">
<div class="elem1">Foo</div>
<div class="elem2">Bar</div>
</div>
$('#my-container').mouseleave(function() { console.log("left"); });

Categories

Resources