I would like to edit a specific attribute from a class in css/JS/JQuery on hover of a different element, but I'm not sure how to do it
eg.
<h1 class="result">Lorium</h1>
<h1 class="result">Ipsum</h1>
<h1 class="result">Dolor</h1>
<img src="example.png" class="images"/>
<img src="example.png" class="images"/>
<img src="example.png" class="images"/>
so that when I hover on one of the <h1> tags, it will change the src of the <img>, but the rest will stay the same. Would I do this in CSS, JS or JQuery? How?
Note: they have to be classes, rather than id's, because I am using PHP to call all these elements and they have to be styled
thanks,
a tired programmer
Firstly you need to detect the hover / mouseenter on the H1 element with the class result.
I am going to assume that all your results have the class result.
$('.result:eq(0)').mouseenter(function(){
console.log("hello world");
});
Next you need to change the img src associated with the result - again I am going to assume all your imgs have the same class.
$('.result:eq(0)').mouseenter(function(){
$('.images:eq(0)').attr('src','https://via.placeholder.com/150x150')
});
I would suggest you to write a function so that you are not having to hardcode the nth value of the class selector.
Further reading: https://api.jquery.com/eq-selector/
If you are not using jQuery - similar logic but you will use document.querySelector('.result')[0] etc.
Further reading: http://mdn.beonex.com/en/DOM/Element.querySelectorAll.html
EDIT -- For nth value where n is the same index number for both result and images
$('.result').mouseenter(function(){
var nValue = $(this).index();
$('.images:eq('+nValue+')').attr('src','https://via.placeholder.com/150x150')
});
First of all, the structure of your HTML does not seem really scalable. I wouldn't count on order of elements. I would instead rewrite the HTML into something as the following:
<div class="result-container">
<h1 class="result">Result title</h1>
<img src="something.png" class="image" />
</div>
And then to handle events using jQuery, you can do something as follows:
function onHoverIn() {
const resultTitle = $(this);
const image = $(this).parent().find('.image')[0];
image.attr('src', 'something-hovered.png');
}
function onHoverOut() {
// same logic
}
$('.result-container .result').hover(onHoverIn, onHoverOut);
Hope that helps!
In jQuery, typically you can change an image like this:
$(".images").attr("src","second.jpg");
But as you can see, because all the images have same class you probably won't achieve what you are looking for. You need something to differentiate images from each other if you are looking to map them to the header tags.
Since you have multiple, you are probably looking at something like:
$('.images').each(function() {
//count the index and flip the image
});
Related
which option among the following is better or used as a standard way to show/hide the html elements
changing element.style.display
adding/removing a separate class called hide {display: none}
any other standard way
PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way
A third way in the answers below https://stackoverflow.com/a/68983509/14478972
I prefer to toggle a class using DOMTokenList.toggle():
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
Well except the first and second, there is the other way.
Which is rendering the element its self.
It has a better security. as the user wont know if there is a hidden element inside the toggle div. Eg when people try to look at the html
Have a look below
I used jQuery as its easier to write. If you are not able to rewrite a JavaScript version will be happy to rewrite for you.
var items = $(".toggle");
var item = {};
// setup the auto toggle
$(".toggle").each(function(el) {
var id = new Date().getUTCMilliseconds() + $(this).index()
item[id] = $(this).find("content")
if (!$(this).hasClass("show")){
$(this).find("content").remove();
}
$(this).attr("id", id)
});
$(".toggle").click(function() {
if ($(this).find("content").length > 0)
$(this).find("content").remove();
else $(this).append(item[$(this).attr("id")])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle">
<h1>click here to toggle content </h1>
<content>
this is a test
</content>
</div>
<div class="toggle show">
<h1>click here to toggle content(start state is visible) </h1>
<content>
this is a test
</content>
</div>
Option 1 would be standard for only hiding the element, but if you would like to add other styles like transitions and pointer events option 2 is preferred
Good Evening helpful people of stackoverflow,
I want to hide the **clicked ** .project-tile-normal and show the appropriate description div .detail-tile.
I read through some articles regarding my question, but i run into a logical brickwall in my head. Needlessly to say, i'm a beginner in jquery and maybe there is a better way to do that, i just didn't find it.
Here's what i found so far as "answers":
Hide Children, Show nth Child - the closest answer to my question
Show and Hide Several Links - this solution makes my head dizzy
My HTML consists of two rows of divs, similar to that simplified representation:
<div class="wrapper">
<div class=".project-tile-normal">some pictures</div>
<div class=".project-tile-normal"></div>
<div class=".project-tile-normal"></div>
<div class=".detail-tile">description</div>
<div class=".detail-tile"></div>
<div class=".detail-tile"></div>
</div>
This is what i have so far coded:
JQUERY
$(document).ready(function(){
$('.project-tile-normal').on("click", function() {
if( $(this).hasClass("active") ) {
$(this).fadeOut(150);
} else {
var itemid = '#div' + $(this).attr('target'); // my own try to get the Element of the divs.
console.log(itemid);
$(this).addClass("active");
$(".detail-tile").removeClass("hidden");
}
});
$('button').on("click", function(){
$(".detail-tile").addClass("hidden");
$(".project-tile-normal").fadeIn(150);
$(".project-tile-normal").removeClass("active");
});
});//document ready
Should i put all the Items in an array and then count it out? Thanks for your help in advance.
First of all remove the . before the class attribute since there is no need of it. As per the jQuery code there is no need of it. If you are using . you need to escape it using \., in the jQuery selector it may be like $('.\\.project-tile-normal') .
Now you can do the rest using index() and eq(),
$('.project-tile-normal').click(function() {
// you can use toggle if you want toggle between the show and hidden
// else use show method
$('.detail-tile').eq($(this).index()).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<div class="project-tile-normal">some pictures</div>
<div class="project-tile-normal">1</div>
<div class="project-tile-normal">2</div>
<div class="detail-tile">description</div>
<div class="detail-tile">1</div>
<div class="detail-tile">2</div>
</div>
Firstly note that your class attributes in the HTML should not contain any . characters.
With regard to the JS, you can link elements by index by retrieving the index() from the clicked element then selecting the matching required element using eq(), something like this:
$('.project-tile-normal').click(function() {
var index = $(this).index();
$('.detail-tile').hide().eq(index).show();
});
Working example
You're declaring your classes wrong in your HTML. It'll be project-tile-normal instead of .project-tile-normal. On doing that you'll be finding your events working. Then you can actually follow those tutorials to pull off your desired behavior on project title click.
I have a page with many dynamically creted div's as seen below:
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
I'm looking for a way to get get a position of an element (eg. If the element is the first instance of, assign id="1" if element is the second instance of, assign id="2".
I'm currently using the following jquery, but am stuck, as Im not sure where to go from here.
$(document).ready(function () {
var numDialogs = $('.open').length;
});
Any suggestions?
Just use:
$('div.open').prop('id', function(i){
return 'openElement' + (i + 1);
});
JS Fiddle demo.
I've deliberately added a prefix string because while numerical ids are valid under HTML5, they remain invalid under HTML4, and are difficult to select using CSS selectors.
References:
prop().
Mark, you can target the element and then add an attribute like so:
$('.open').attr('id', numDialogs);
This will give it all 4's in this case, but I'll leave you to wrestle with the actual logic to implement the right numbers. Good luck.
Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element
I'm trying to figure out if something like this would be possible. We are given that HTML structure
<a href='#' class='anyLink'>
<!-- here goes some content-->
<div class='childElement'><!-- here goes some content--></div>
</a>
I am not able to use ID's because there are many links and it's not defined how many more are to come. So my question is, do you guys know a way where I can do something like this :
$('a').on("click",function(e){
$(this +"div").val(); // for example.
});
I want to select a children element of that anchor that has been clicked or want to get the value of the children element. I also don't have any ID's of the children elements and I am trying to select things via CSS Selectors as td:nth-child(4).
Could anybody tell me if this is possible ?
try
$('a').on("click",function(e){
$("div",this).text(); // for example.
});
$('a').on("click",function(e){
$(this).children("div").eq(0).html();
});
You are looking for a function called .children().
But you can also try something like this:
$('a').on('click', function( e ) {
$('div', this).val(); // Each div child of this element
$(this).children('div'); // Each div child of this element
});