jquery hide element if href is equal to - javascript

I recently made a jquery code that should hides an element if it's href is equal to another element's but i can't be able to make it work...
jsfiddle
HTML
<div class="a">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>
CSS
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
JQUERY
var mainhref = $(".a a").attr('href');
if($("a", this).attr('href') == mainhref ) {
$(".a").hide();
}
else {
$(".a").show
}

Using plain javascript :D
let ar = document.getElementsByTagName('a'),
holdarray = [];
Array.from(ar, elem => {
if(holdarray.includes(elem.getAttribute('href')))
elem.parentNode.style.display = 'none'
else
holdarray.push(elem.getAttribute('href'))
})
.a { width:400px;height:100px;background-color:black; }
.thumb { width:400px;height:100px;background-color:green; }
.b { background-color:yellow; }
<div class="a" >
</div>
<div class="thumb">
</div>
<div class="thumb b">
</div>

You can try like this, only check for thumb class then it will hide specific div which contain same href
var mainhref = $(".a a").attr('href');
$('.thumb a').each(function(){
if($(this).attr('href') == mainhref)
{
$(this).parents('.thumb').hide();
}
});

Just select by that href (and parent not containing the base div's class 'a') and hide it
$('a[href="'+mainhref+'"]').parent(":not(.a)").hide();
var mainhref = $(".a a").attr('href');
var parentDiv = $('a[href="'+mainhref+'"]').parent(":not(.a)").hide();
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a" >
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>

Try something like this with Jquery.
Loop on each a and store the href. Select all <a> but first with same href and hide the parent
$("a").each(function(){
var href= $(this).attr("href");
$("a[href='"+href+"']").not(":first").parent().hide();
});
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>

You should loop through all elements.
$('a').each(function(){
if($(this).attr('href') == mainhref){
$(this).hide();
}
});

$('a').each(function(){
if($(this).attr('href') == mainhref){
$(this).hide();
}
});

Here's a trick, using the radio:checked.
$($("a").toArray().reverse()).each(function(index, el){
var href = $(el).attr('href');
$(el).parent().before('<input type="radio" name="' + href + '" class="hidden" checked />');
})
The reason that I use reverse is that I want the first a tag to remain showing. If you want the last a tag to remain, you can just use $('a') instead of $($("a").toArray().reverse())
css:
.hidden { display:none };
input[type=radio]+ div a { display: none };
input[type=radio]:checked + div a { display: block };
With this trick, you can make all the a tag with a unique href. Hope it can help you.

Related

How can I change only the hovered element's styling while looping through elements and using addEventListener?

I have a few div's with class ".web-item" containing images. I go through them with a for loop and put an addEventListener (mouseover) on all the iterations and try to change the styling of each element (always the hovered element's style). But as I hover over an element, the styling of all the elements changes following the hovered element.
This is my JavaScript code:
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
And the HTML:
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
</div>
How could I achieve that only the actually hovered element's styling changes? I would be really grateful for your help.
Only the styling of the hovered element will change - but if you hover over another element afterwards (like if you're moving the mouse quickly), that element's style will change too. You don't have any "stop hovering" functionality at the moment - if the mouse hovers over something, that element's style will stay changed until the page is reloaded.
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
While you could add a mouseout listener, this can be achieved with only CSS and :hover:
.web-item-caption {
display: none;
}
.web-item:hover {
filter: brightness(30%)
}
.web-item:hover > .web-item-caption {
display: block;
}
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
text 1
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
text 2
</div>

How to write a document.querySelector for the following code

I'm having difficulty writing the document.querySelector for the following code. Currently I've written this code as querySelector but it does not encompass everything...
Please help me improve this, thank you.
Edit: as there seemed to be some confusion, let me elaborate. I would like all the elements, from div, a, img, everything to be encompassed in the querySelector.
var areaa = document.querySelector("#menu #envelope #links");
<div id="menu">Click here to browse the internet.
<div id="envelope">
<div id="links" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
Edit 2 - as more code was required (the href elements are removed / added as needed)...
var menu = document.getElementById("menu");
var areaa = document.querySelectorAll(".areaa");
menu.addEventListener("mouseenter", addHref);
//areaa.addEventListener("mouseleave", remHref);
document.addEventListener("mousemove", function(){
if(this != areaa){
remHref();
}
});
menu.addEventListener("click", addHref);
document.addEventListener("click", function (){
if (this != areaa){
remHref();
}
});
var g = document.getElementById("g");
var s = document.getElementById("s");
function remHref (){
if (g.hasAttribute("href")){
g.removeAttribute("href");
}
if (s.hasAttribute("href")){
s.removeAttribute("href");
}
}
function addHref (){
setTimeout(activate, 250);
}
function activate (){
document.getElementById("g").setAttribute("href", "https://www.google.com");
document.getElementById("s").setAttribute("href", "https://www.example.com");
}
you might want to add a class to all elements you want to be captured, then use document.querySelectorAll
var areaa = document.querySelectorAll(".my-class");
html shoud look like this:
<div id="menu" class="my-class">Click here to browse the internet.
<div id="envelope" class="my-class">
<div id="links" class="my-class">
<div>
<a id="g" class="redirect">
<img class="my-class" id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
If you want to select everything you can use the below:
var areaa = document.querySelectorAll("#menu #envelope #links *");
If you want to be more specific you can do the following (the code below will select all of the anchor tags and images inside #links):
var areaa = document.querySelectorAll("#menu #envelope #links a, #menu #envelope #links img");
You can use querySelectorAll
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Learn more: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use it like this:
var areaa = document.querySelectorAll('*');
This will return all items.
You can replace document with the container if you want to restrict this to a specific div.
2 things, either add a class to every div
<div id="menu" class="area">Click here to browse the internet.
<div id="envelope" class="area">
<div id="links" class="area" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
and select all divs by
let areaa = getElementsByClassName("area");
or you can use document.querySelectorAll("yourclassname") to access all divs of that class name

Change image of specific clicked element

I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG
<!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->
<ul class="list-unstyled">
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
</ul>
Here is my jquery:
function handler( event ) {
var target = $( event.target );
if ( target.is( "img" ) ) {
target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
}
}
Thank you.
You can add click event on img that exist in ul and toggle src of them by saving in data attribute. For toggling you need to save main src of image that can be saved as data-src (or anything else), And you need a flag for state of image like data-clicked (or anything else).
$('ul.list-unstyled li img').on('click', function(){
var clicked = $(this).data('clicked');
if(clicked === '1') {
$(this).attr('src', $(this).data('src'))
$(this).data('clicked', '0')
} else {
$(this).data('src', $(this).attr('src'))
$(this).attr('src', "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
$(this).data('clicked', '1')
}
})
img {
height: 25px;
padding-right: 4px;
}
li {
margin: 4px;
clear: both;
}
li:nth-child(odd) {
background: #f0f0f5;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->
<ul class="list-unstyled">
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
</ul>
What you need to use is jquery's attr() function
Give your image a class name then you can change the src in jQuery by:
$(".image1").attr("src","https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
And to attach it to a click event
$(".image1").click(function(){
$('.image1').attr('src','https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png');
});
add an ID to your image and then try this:
$(function() {
$("#yourImage").onClick(function() {
$(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
});
});
Alternatively, you can change the image depending on the source like this:
$(function() {
$("img").onClick(function() {
if ($(this).attr("src") == "OriginalSource")
$(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
});
});

how to get the href of a link when i press another href

i want to get the attr href of an above link beside the one i press wich is the last link from productinfo div class. I tryed with closest but it gets me the same link i press and i want the above one. The link i want to store in produs_href is the link from first href under productinfo class. Here is my code:
<div class="col-sm-4 produse"><!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="/images/produse/'.$recomand['ID_Produs'].'/'.$recomand['Poza'].'" alt="" />
<h2 style="text-decoration: line-through;">'.$recomand['Pret'].' lei </h2><h2>'.$recomand['Pret_Nou'].' lei </h2>
<p>'.$recomand['Nume_Prod'].' '.$recomand['Gramaj'].' '.$tip.'</p>
<i class="fa fa-shopping-cart"></i>Adaugă în coș
</div>
</div>
</div>
</div>
jquery
<script>
$(".cos").click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('a').attr('href');
$.getJSON(href, function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#test").append('<li>' + val.nume + '</li>')
$("#cnt").append('' + val.cnt +'')
});
});
$(\'#detalii_prod\').modal('show');
alert(produs_href);
});
</script>
Use prev. This method gets the immediately preceding sibling.
$(this).prev().attr('href');
EDIT
From your comments, the code that would do the trick is
$(this).closest('.productinfo').find('a:first').attr('href');
You can use the .prev
var link = $(this).prev().attr('href');
and now you can use link.
you can use like this
$(this).prev("a").attr("href");
and more help:
Get the href value of a previous HTML anchoer, <a>, using jQuery
$(".cos").click(function(e){
e.preventDefault();
var text = $(this).parent().find('a:first').attr('href');
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 produse">
<!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center"> <img src="img/Penguins.jpg" height="50" width="50" alt="" />
<h2 style="text-decoration: line-through;">Hello there</h2>
<h2>Anto</h2>
<a href="link produs">
<p>Angeline</p>
</a> <i class="fa fa-shopping-cart"></i>Test </div>
</div>
</div>
</div>
try this
$(this).parent().find('a:first').attr('href');
Try with .eq() method.
$(this).parent().find('a').eq(0).attr('href');
Hope this helps you...

How to get each element and assign them an inline style contained inside the child

I've been looking for an elegant solution for a day now and I am pretty new to jQuery.
I would like to get each .figure and assign them an inline style where the value is contained inside the child element via a custom data- attribute :
<div>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-01-thumbnail.png" src="images-01.png" />
</div>
<div class="content">
<h3>Sale</h3>
<h4>Discover our latest styles</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-02-thumbnail.png" src="images-02.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-03-thumbnail.png" src="images-03.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
</div>
In other words, the results would be :
...
<div class="figure" style="background: url(images-01-thumbnail.png);">
...
<div class="figure" style="background: url(images-02-thumbnail.png);">
...
<div class="figure" style="background: url(images-03-thumbnail.png);">
...
Also, I'm always ready something about jQuery so if you have any books about JavaScript or jQuery to suggest, that is always appreciated.
You can iterate over all .picture elements, find the image descendant and read its data attribute:
$('.figure').css('background', function() {
return 'url(' + $(this).children('img').data('thumbnail') + ')';
});
Some methods, like .css even accept functions so that you can iterate over the selected elements implicitly.
Reference: .css, .children, .data
you can iterate over each item with the class thumbnail and set the css property to the closet div.
$('.thumbnail').each(function() {
var $this = $(this),
$background = $this.data('thumbnail');
$this.closest('.figure').css({background : $background} )
});
This should work
$("[data-thumbnail]").each(function ()
{
var $this = $(this), url = $this.data("thumbnail");
$this.parents(".figure").css("background-image", 'url("' + url + '")');
});
How about this (Working code example: http://jsfiddle.net/jpbH2/2/):
var pathToImages = "/";
$(".figure img").each(function(){
$(this).parent().css({"background": "url(" + pathToImages + $(this).data('thumbnail') +")"})
});
Edit
I actually didn't notice the data-thumbnail. Edited my answer above

Categories

Resources