Hover and selectors - javascript

I am completely new to Javascript / Jquery and I have a problem.
Suppose in my html page I have a number (undefined) of class to hover (when I hover something happens). Here I put 2 examples.
<div class='hover' id='hov33749'>Wikipedia</div>
<div class='hover' id='hov32747'>Google</div>
How to :
Apply a function when I hover on Google or Wikipedia
Retrieve the div corresponding to the hover (id, text, position on the page etc.)
I tried to put a random id and put some regex but it doesn't work well
I thank you in advance

Since you are starting out with JavaScript, I'd suggest refrain JQuery for now and understand how the language itself works.
The following code adds an eventListener to all elements with class hover, the functionality of which is in onHover method
const onHover = (e) => {
const id = e.target.id;
const text = e.target.textContent;
console.log(id, text);
}
const hover = document.querySelectorAll(".hover");
hover.forEach(item => item.addEventListener("mouseover", onHover));
<div class='hover' id='hov33749'>Wikipedia</div>
<div class='hover' id='hov32747'>Google</div>

See JQuery documentation
.hover()
$(".hover").each(function(){
$(this).hover(function(){
// Do something ...
console.log("Text: " + $(this).text() + ", Id: " + $(this).attr("id"));
});
});

Related

Change location.href with jQuery

I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>

I want to get the text content of an element inside $(this) on jQuery

function newFunc(){
excuseDivs = " "
excuseArrayItem = excuse + " : " + "<span class='excuseDivTime'>" + endTime + "</span>";
excuseArray.unshift(excuseArrayItem)
excuseArray.forEach(function(excuse){
excuseDivs +="<div class='excuse-div'>"+excuse+"</div>"
})
I want to add a click listener to the div that this function creates. I want that click listener to get the text content of the span inside the div (class of excuseDivTime). Is there some way to get something like ($(this) > span).textContent ??
You can do this fairly easy in either plain JavaScript or stick with jQuery.
You need to query for the span under the clicked div.
If you are using jQuery, stick with jQuery method calls e.g. .text() instead of .textContent.
// Plain JavaScript
document.getElementById('MyDiv').addEventListener('click', function(e) {
alert(e.currentTarget.querySelector('span').textContent);
});
// jQuery Version
$('#MyDiv').on('click', function(e) {
alert($(this).find('span').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="MyDiv">Click me! <span>This text will show in an alert.</span></div>
Use find() or children()
$(document).on('click', '.excuse-div', function() {
console.log( $(this).find('.excuseDivTime').text() );
});

Mouseover image stays the same

I have a problem with this code
I'll explain a little how this works,
The idea of this is that when hovering in tag (a), change the image of the id="meal", by the one that is in the (data-meal = "meal-14") .. in a few words
The pre-determined image is meal-0.png, hover in tag (a) with (data-meal = 14), replaces the url of the image with (meal-14.png),
Everything works fine, I only have one problem and is that when you stop hovering, do not go back to the pre-determined image, it stays in the image that became hover. Should return to the image meal-0.png.
<div class="imagen-hover" id="meal">
<img src="/public/tienda/meal-0.png" alt="">
</div>
<ul>
<li><a class="carne-a" data-meal="meal-14">14. Punta de Anca</a></li>
<li><a class="carne-a" data-meal="meal-16">16. Chata Angosta</a></li>
</ul>
jQuery(document).ready(function($) {
var path = "/public/images/";
$(".meal-a").on("mouseover", function() {
var meal = $(this).attr("data-meal") + ".png";
$("#meal img").attr("src", path + meal)
});
});
that is because it is doing exactly what you told it to do.
you need to make another event handler for mouseleave
or you can look at the jQuery docs , mouseenter can take two call backs , one for entering and one for leaving
$(".meal-a").mouseenter( function() {
var meal = $(this).attr("data-meal") + ".png";
$("#meal img").attr("src", path + meal)
}).mouseleave( function() { //for when mouse leaves
});
What I would recommend though... you do not need javascript or jQuery at all for this , there is a css selector for while the user is hovering over an element
.meal-a{ // regular code
}
.meal-a:hover{ // hover code
}
Also add a "mouseout" function to handle returning the image to its previous value
$(".meal-a").on("mouseout", function() {
$("#meal img").attr("src", "meal-0.png")
});

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

Javascript mouse over on dynamic amount of elements

My goal is on hover a p element contained inside an a tag gets bigger on hover. I have achieved this via css3 transitions, however this is not the issue.
A loop creates a variable amount of elements in the form below on each iteration.
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPT oneplustwo\" alt=\'"+ image_website +"' style=\"cursor:pointer;width:"+ itemWidth + "px"+";height:"+anchorHeight+";position:absolute;left:"+ locationLeft + "px"+";top:0.3%;\" ><p id=\"test\" class=\"popupDynamic\"> " + popupImageTitles[i] + "</p>";
anchorElement += '</a>';
I would love to be able to add a mouse in/out effect whenever the user scrolls on the relevant anchor. each p tag contains unique information that needs to be conveyed and on hover only the relevant one should react.
I dont want to it it the below way, making two each of the methods every time a new element is created above. is there a way to have the following below which will work for a dynamic amount of elements?
$("#anchor" + etc).mouseover(function() {
document.getElementById("test").style.height="1.1em";
});
$("#anchor" + etc).mouseout(function() {
document.getElementById("test").style.height="1.1em";
});
My version of suggestions. the console logs works.
.popupHighlight {
color: red;
}
..
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(e.target).next('p').addClass("popupHighlight");
});
$('.boxOPToneplustwo').mouseout(function (e) {
$(e.target).next('p').removeClass("popupHighlight");
});
What about selecting all a elements?
$('a').mouseout(function() {
//do stuff in here
});
or better yet, have a class selector:
$('.mySpecialRolloverClass').mouseover(function (e) {
$(e.target).next('p').addClass("highlight");
});
$('.mySpecialRolloverClass').mouseout(function (e) {
$(e.target).next('p').removeClass("highlight");
});
which would go hand in hand with
An anchor
and
.highlight {
color:red;
}
Here's a jsfiddle demo:
http://jsfiddle.net/8J6kM/
The #yochannah answer is correct, however if you want to add more links dynamically, you then need to use on method instead of mouseover and mouseout, otherwise it won't work. See the demo and jQuery documentation for further details.
// I assumed that links are placed inside of a container element: #links
$('#links').on('mouseover', '.mySpecialRolloverClass', function (e) {
$(e.target).next('p').addClass("highlight");
});

Categories

Resources