Get a href Title and change on click - javascript

I have a series of links set in an image gallery and I need a way to display the color to the user. Currently the color name is stored in the a href title of the link to the image in the gallery.
<div class="select-option swatch-wrapper selected" data-attribute="pa_luxcraft-2" data-value="redblack">
<img src="/ay/wp-content/uploads/2017/01/Center-Table-Red-Black-32x32.jpg" alt="thumbnail" class="wp-post-image swatch-photopa_luxcraft-2_ swatch-img" width="32" height="32" data-pin-nopin="true">
</div>
In this case it is Red/Black for the color
Each time an image is clicked it gets assigned the class of "selected"
I know I can get the title with a simple variable of
var title = $(this).attr('title');
But I am unsure of how to get it when the class of selected is applied.

I included a couple of examples to help get you started.
<div class="displayToUser"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$("a").click (function () {
$(document).css("background",$(this).attr("title")); //set's background to color, just to let you know how to do that.
$(this).attr("title","new title"); //changes title if that's what you want
$(".displayToUser").html(
$(this).attr("title")
); // sets an element to show the contents of title, just so that you know how to do that
$(this).hasClass("selected"); //if you want to check to see if it has the class selected
$(this).addClass("selected"); //to add the class selected, if that's what you're looking for.
});
</script>

var color;
if ($(this).hasClass('selected')) {
color = $(this).attr('title');
}
and so on...

var valueoftitle = $('.selected')[<your_index>].attr('title');
Edit:
With $('.selected') you get a array back with all the elements with class .selected. Then you can access those elements with the square brackets with the index of the element that you want to access. After that you have the element and you can do with it whatever you want, like in this example: .attr('title'), which would give you back the value of the attribute 'title'. You can use this in any way possible like a for loop, foreach loop or just as inline with an index.

You mentioned that the selected class is applied when the image is clicked. Assuming you have a click handler bound to the image, you could pickup the title attribute from the parent link with $(this).parent('a').attr('title')

Related

How to search element by class and retreive title attribute in Javascript (greasemonkey)

I'd like to select this element:
<span class="score likes" title="22">22 points</span>
such as: var likes = comment.getElementsByTagName('score likes').title;
and then return the value of "title" tag.
I've found lots of posts on how to select element by class or title, but I haven't been able to find how to select element by class and then get the value of title to save to a variable. This is for a grease-monkey script.
Edit: This is NOT a duplicate question, does anyone ever read the question before flagging for duplicate questions? To be extra clear, I do NOT want to search by the TITLE tag, I want to GET the value of the title tag and save it to a variable. I do not know what the value of the title tag is before searching.
Taking some liberties for your original selection method (getElementsByTagName => querySelector) , you can access your element's attributes using getAttribute():
var likes = comment.querySelector('.score.likes').getAttribute('title');

onmouseover & onmouseleave functions not working properly

I'm new to this site and relatively new to web development. I was trying to incorporate javascript to this webpage I made with just HTML & CSS. This webpage is basically an online store for certain products and what I was trying to do was that when someone has their mouse over one of the products, it would provide some details such as the name of the product and the price and when they move the mouse out, it would go back to just an image of the product. For some reason, with my code, it will change the elements so that it shows the details but it won't change back to the original image after the mouse moves away.
I've tried everything I could think of and the goal of this project was to make sure I had an understanding of javascript so I was trying to do this without any jquery. Any advice would be greatly appreciated.
Here is the code:
//Holds all div elements with class attribute "productlink" which hold the product images
var products = document.getElementsByClassName("productlink");
//When this function is called, the product image is changed to show an image of the product, the name and price
//classNum - specifc class element being called
//priceAmount - price of product
//describe - Description/Name of the product
function hoverDetails(classNum, priceAmount, describe) {
//Div container for details, image of product, price of product and description
var divContainer = document.createElement("div");
var image = document.createElement("img");
var price = document.createElement("p");
var description = document.createElement("p");
var priceTextNode = document.createTextNode(priceAmount);
var descriptionTextNode = document.createTextNode(describe);
description.appendChild(descriptionTextNode);
price.appendChild(priceTextNode);
image.src = picArray[classNum];
divContainer.setAttribute("class", "newdiv");
image.setAttribute("class", "newimg");
price.setAttribute("class", "itemprice")
description.setAttribute("class", "itemdescription");
products[classNum].parentNode.style.textDecoration = "none";
divContainer.appendChild(image);
divContainer.appendChild(description);
divContainer.appendChild(price);
//This should replace the current image with the details specified eariler
//childNode is set to 1 due to a #text node in the div
products[classNum].replaceChild(divContainer, products[classNum].childNodes[1]);
}
//This function, when called, replaces the detailed product with just an image of the product
function originalImage(classNum) {
var image = document.createElement("img");
image.setAttribute("class", "display_image");
image.src = picArray[classNum];
products[classNum].replaceChild(image, products[classNum].childNodes[1]);
}
Here is the element that is referencing these functions:
<a href="#">
<div class="productlink" onmouseover="hoverDetails(0,'$85.95','Printer') "onmouseout="originalImage(0)">
<img class="display_image" src="images/printer1.jpg" />
</div>
Don't the mind the variable names and I'm sorry if my code seems too much. Any help would be appreciated.
EDIT: Just to let people know, both functions work. The onmouseleave event works when the onmouseover event is not attached. Additionally, the code works when the onmouseover event is replaced with onclick. When I replace onmouseover with onmouseenter, the code works once but never again. This is very strange.
There is actually another mouse event called onmouseout. Add another attribute called onmouseout="removeHoverDetails()" and then inside of removeHoverDetails() select everything and say .visibility = "hidden"; Or whatever way you want to use to get rid of the elements in the popup. Also check out w3schools tutorial on onmouseover and onmouseout: http://www.w3schools.com/jsref/event_onmouseover.asp
Okay I found the solution to my problem. I put the onmouseover event on the image element of the "productlink" div an left the onmouseout event on the div and looks to be working fine.

How to get the default colors of a link?

I need some JavaScript to find the default link color of a page. How do I do it? I looked around but not sure how to do it. I believe jQuery has a .css function I can use but how about regular JavaScript?
Please note I don't have any specific element to target to grab css from, i.e. I can't look for the a color value for #myID -- I need to find the default a color value for the links on the page.
Thanks!
Try: Just place an <a> at the top of your page. This will get the values from the first <a> element.
Without any pseudo elements
window.getComputedStyle(document.body.getElementsByTagName('a')[0], null).getPropertyValue("color");
active
window.getComputedStyle(document.body.getElementsByTagName('a')[0], ':active').getPropertyValue("color");
hover
window.getComputedStyle(document.body.getElementsByTagName('a')[0], ':hover').getPropertyValue("color");
If you have any fears, just go with:
var el = document.createElement('a'); // Creates <a>
document.body.appendChild(el);
var COLOR = window.getComputedStyle(el).getPropertyValue("color");
document.body.removeChild(el);
You can create an element and add it to html, then get the CSS properties of the element that is assigned by default. Example:
var element = document.createElement('a');
document.documentElement.appendChild(element);
var color = getComputedStyle(element).color;
console.log(color) //rgb(0, 119, 204) stackoverflow default link color
Try this on StackOverflow page, opening the console.
Demo

Change Dynamic Link Text In Javascript

I currently have a slideshow run with HTMl CSS and JS at the moment for the navigation buttons below the slideshow it is just placing numbers instead of text. Is there a way to grab the images title and use it or custom text for each slide link. Below i included the Javascript that makes the navigation buttons and adds the text. If you need anything else just let me know.
If i can just specify text in this JS file that would work too.
Also if it may help im using Kickstart HTML Template.
Link to view it http://bliskdesigns.com/clients/timbr/
var items = $(this).find('li');
wrap.append('<ul class="slideshow-buttons"></ul>');
items.each(function(index){
wrap.find('.slideshow-buttons')
.append('<li>'+(index+2)+'</li>');
});
It's difficult to give you a concise answer with what you've provided, however:
Assuming that in the code you've provided:
items is an array containing each slide in your slideshow;
That each element in items contains an img;
That the text that you want to appear in the slideshow nav is the title attribute of each img;
That the unordered list being built by wrap is the navigation;
That the text you want to change is the numeral within the anchor of each item injected into wrap.
Here's a potential answer:
// put all slides into 'items'
var items = $(this).find('li');
// append the wrap element with an unordered list
wrap.append('<ul class="slideshow-buttons"></ul>');
// loop over each item
items.each(function(index){
// grab the title attribute of the img child of this instance of items
var titleText = $(this).find('img').attr('title');
// push a new <li> into 'wrap'
wrap.find('.slideshow-buttons').append('<li>'+titleText+'</li>');
});
This should just be a direct replacement for wherever in your project the code you've included above came from.
As I say: I can't promise that this will work without a lot more information, but in theory it will. Make sure that each of your images has a title:
<img src="/link/to/image.kpg" alt="alternative text" title="text you want to appear in the slider navigation" >
Alternatively, you can use the text in the image's alt tag instead by changing this line from above:
// grab the alt attribute of the img child of this instance of items
var titleText = $(this).find('img').attr('alt');
In the list items you can add the text that you want to display instead of numbers, as shown below.
<li data-displayText="Timber Mart"> <img src="http://i.imgur.com/4XKIENA.png" width="920" /> </li>
Then in above code you can use the text instead of index, as shown below.
wrap.find('.slideshow-buttons')
.append('<li>'+$(items[index]).attr("data-displayText")+'</li>');

SImple image replace using Javascript/html

Couldn't find a punctual answer for this simple task and your help is highly appreciated
We have an image we want to switch based on user's color selection.
Tried several methods, none worked.
This is the idea:
$('#YourButton').click(function() {
var oldSrc = 'images/Image1.png';
var newSrc = 'images/Image2.png';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
});
Just change the image source with javascript by clicking your button with another color
Note: it´s jquery so you have to include the js file..
Just bind a click listener to your button and change the src attribute of your image.
$('#colorButton').click( function() { //choose a new color
$('#imageIcon').attr('src', 'path/to/new/image.png'); //change the img's source
});
EDIT (response to questions):
If you want this code to apply to all of your buttons, give each of your buttons a similar class instead of an ID:
<div class="colorButton"></div>
Then you can use the following selector to apply the above click listener to all of these divs:
$('.colorButton')
Naturally, you want to change your image as simply as possible. You could map all of your colors to their corresponding image file, but as far as design goes this might get messy and unwieldy. I would create a directory that stores all of your image files (for example, /your/color/swatches) and give each of them a name consistent with their color, like 'ff0000.png' for red, '0000ff.png' for blue, etc.
Why would we do this? So that we can switch your image based on the background-color attribute of your buttons. Let's say that you have the following buttons:
<div class="colorButton" style="background-color: '#ff0000'"></div>
<div class="colorButton" style="background-color: '#0000ff'"></div>
You can use the same click listener, but it will have to be modified a bit since we are mapping the background color to an image:
$('.colorButton').click( function() {
var color = $(this).css('backgroundColor');
//(You'll need to modify your color string here)
$('#imageIcon').attr('src', 'your/color/swatches/' + color + '.png');
});
BUT this won't work yet. Since most browsers return "rgb(xx, yy, zz)" from .css('backgroundColor'), you need to convert that string into hex. This post on SO gives a more or less effective way to do so, but you'll need to modify it to fit your model where I have indicated.

Categories