jQuery Issue cannot retrieve or set attributes, 'undefined' - javascript

I have an img element. That image element, on mouse hover, will display a detailed tool tip.
I'm trying to make the img element default start empty null, and feed it the image information from the tooltip on load.
I can't retrieve or assign attributes though using $('idName').attr(a,b);
html and js below:
<div class="col-sm-6 text-left">
<h1>Member Equipment</h1>
<p>-Show member equipment-</p>
<table class="table">
<tbody>
<tr>
<td><img id="primary" class="img-responsive" src="" alt="Primary"
onmouseover="document.getElementById('primary_tool_tip').style='display:block'"
onmouseleave="document.getElementById('primary_tool_tip').style='display:none'">
<div id="primary_tool_tip" class="bottom" style="display:none">
<img id="tooltip_img" src="../images/sword01.jpg" />
<div id="tooltip_name">Bronze Sword</div>
<div id="tooltip_equipslots">Primary, Secondary</div>
<div id="tooltip_attributes">STR+2 DEX+2</div>
<div id="tooltip_elements">Fire+5</div>
</div>
</td>
<td id="secondary"><img class="img-responsive" src="" alt="Secondary"></td>
<td id="ranged"><img class="img-responsive" src="" alt="Ranged"></td>
<td id="ammo"><img class="img-responsive" src="" alt="Ammo"></td>
JS
alert($("tooltip_img").attr("src"));
function initialize(){
$('primary').prop('src', $('tooltip_img').attr('src') );
}
window.addEventListener("load", initialize, false );

Place all of your JavaScript in a JQuery document.ready() function so that it doesn't execute until after the DOM has been loaded and is ready to be interacted with.
Then, make sure that you are using correct selectors.
Tag Name gets elements by the element name.
Prepending # gets elements by ID
Prepending . gets elements by class name
So all together:
// The contents of an anonymous function that is passed to JQuery
// won't run until the DOM is parsed and ready to be interacted with.
// This is also known as a "document.ready()" function.
$(function(){
alert($("#tooltip_img").attr("src"));
function initialize(){
$('#primary').prop('src', $('#tooltip_img').attr('src') );
}
window.addEventListener("load", initialize, false );
});

You need to $("#primary") to target element by id.
in your case : $("primary") will try to find an HTML element named <primary>

I fiddled around with what Scott gave me made some minor adjustments and everything works now =).
My img is now instantiated from information contained inside my tooltip's bundle of information. Which will eventually be supplied itself from js, and js will supply it through xml externally if things go accordingly.
Thanks for help Scott and company, final refined code below:
Final code
HTML
<div class="col-sm-6 text-left">
<h1>Member Equipment</h1>
<p>-Show member equipment-</p>
<table class="table">
<tbody>
<tr>
<td>
<img id="primaryIcon" class="img-responsive" src="" alt="Primary"
onmouseover="document.getElementById('tooltip_primary').style='display:block'"
onmouseleave="document.getElementById('tooltip_primary').style='display:none'">
<div id="tooltip_primary" class="standardtooltip">
<img id="tooltip_primary_img" src="../images/sword01.jpg" />
<div id="tooltip_primary_name">Bronze Sword</div>
<div id="tooltip_primary_equipslots">Primary, Secondary</div>
<div id="tooltip_primary_attributes">STR+2 DEX+2</div>
<div id="tooltip_primary_elements">Fire+5</div>
</div>
</td>
<!--
<td>
<img id="secondaryIcon" class="img-responsive" src="../images/sword01.jpg" alt="Secondary"
onmouseover="document.getElementById('tooltip_secondary').style='display:block'"
onmouseleave="document.getElementById('tooltip_secondary').style='display:none'">
<div id="tooltip_secondary" class="tooltip" style="display:none">
<img id="tooltip_secondary_img" src="../images/sword01.jpg" />
<div id="tooltip_secondary_name">Bronze Sword</div>
<div id="tooltip_secondary_equipslots">Primary, Secondary</div>
<div id="tooltip_secondary_attributes">STR+2 DEX+2</div>
<div id="tooltip_secondary_elements">Fire+5</div>
</div>
</td>
-->
<td id="ranged"><img class="img-responsive" src="" alt="Ranged"></td>
<td id="ammo"><img class="img-responsive" src="" alt="Ammo"></td>
JS
$(function(){
initialize();
});
function initialize(){
document.getElementById("primaryIcon")
.setAttribute("src", $("#tooltip_primary_img").attr("src"));
alert('working as intended!');
}

Related

Add number to end of div with jQuery

I'm using jQuery to create a simple addClass on hover. Hovering over a #science-panel-number div triggers a class of .active to be added to an #iphone-screen-number div.
Here is my jQuery:
$('#science-panel-1').hover(function(){
$('#iphone-screen-1').addClass('active');
},function(){
$('#iphone-screen-1').removeClass('active');
});
$('#science-panel-2').hover(function(){
$('#iphone-screen-2').addClass('active');
},function(){
$('#iphone-screen-2').removeClass('active');
});
$('#science-panel-3').hover(function(){
$('#iphone-screen-3').addClass('active');
},function(){
$('#iphone-screen-3').removeClass('active');
});
My HTML:
<div class="col-md-4">
<div id="science-panel-1" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-2" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-3" class="science-panel__item">
Content goes in here!
</div>
</div>
<div class="col-md-4">
div id="iphone-screen-1" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
div id="iphone-screen-2" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-3" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-4" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-5" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-6" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
</div>
<div class="col-md-4">
<div id="science-panel-4" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-5" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-6" class="science-panel__item">
Content goes in here!
</div>
</div>
This feels like a lot of code to do the same script. Is there a way to have one piece of script that can add the numbers it self? As #science-panel-1 will always link to to #iphone-screen-1 and so on.
This will do what you need. Just apply the handlers to elements whose ID begins with science-panel-, which should cover all of them...
$("[id^=science-panel-]").hover(function() {
// get the corresponding iphone-screen element id
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).addClass("active");
},function() {
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).removeClass("active");
});
I recommend changing the markup to include the data you need to drive the script:
<div data-target="#iphone-screen-1" id="science-panel-1" class="science-panel__item">...</div>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This allows you to select all the science panel items at once:
$('.science-panel__item')
and perform the exact same script on each of them:
$('.science-panel__item').hover(function () {
$($(this).data('target')).addClass('active');
// ^^^^^^^^^^^^^^^^^^^^^^
// use the data-target attribute as a selector
}, function () {
$($(this).data('target')).removeClass('active');
});
If you change the attribute and the selector, you'll have a reusable feature you can apply to any element:
$('[data-hover-target]').hover(function () {
$($(this).data('hoverTarget')).addClass('active');
}, function () {
$($(this).data('hoverTarget')).removeClass('active');
});
I'd firstly ask if the active class is strictly necessary? Can what you want be achieved with CSS if it is for styling only by using the :hover pseudoclass?
If you do need the .active class for some reason, I would change the markup to be a little more generic so that all the science panels had a CSS class of .science-panel and all the iphone screens had a class of .iphone-screen. Then you could simplify the JS to look like
$('.science-panel').on('mouseenter mouseleave', function(e) {
$(this).find('.iphone-screen').toggleClass('active', e.type === 'mouseenter');
});
This will find the .iphone-screen inside of the .science-panel that you hover over and toggle the class to on if the mouse enters and off when the mouse leaves it.
edit: I see you've updated your answer to include your markup, this answer was assuming that your iphone-screens were nested in the science-panels so this won't necessarily work for you if you don't/can't nest your markup

Add href link to Image that has been displayed via js click

Similar to a question I asked recently but the previous was using mouse over so was rubbish for touch screen.
This is 3 divs with images. on click they individually change to a second image and reset the other 2 to a standard image. this all works ok.
But when the second image in any of the divs is active i would like to be able to click this image and navigate to a different page.
Clearly adding href to the html just navigates and ignores the JS effect.
Thanks for reading.
$(document).ready(function(){
$('#s1').click(function(){
$('#s1').attr('src', 'images/object/click-1.png');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/standard-3.jpg');
});
$('#s2').click(function(){
$('#s1').attr('src', 'images/object/standard-1.jpg');
$('#s2').attr('src', 'images/object/click-2.png');
$('#s3').attr('src', 'images/object/standard-3.jpg');
});
$('#s3').click(function(){
$('#s1').attr('src', 'images/object/standard-1.jpg');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/click-3.png');
});
});
<div id="section3" class="container-fluid" align="center">
<div class="row row-centered ">
<div id="top-box-1" class="col-sm-4">
<img src="images/object/standard-1.jpg" class="std" id="s1" width="300" height="300"/>
</div>
<div id="top-box-2" class="col-sm-4">
<img src="images/object/standard-2.jpg" class="std "id="s2" width="300" height="300"/>
</div>
<div id="top-box-3" class="col-sm-4">
<img src="images/object/standard-3.jpg" class="std" id="s3" width="300" height="300"/>
</div>
</div>
</div>
You can see if the src now contains 'click'. if not then swap the src and return false to stop the href:-
$('#s1').click(function(e) {
if (!$(this).is('[src*="click"]')) {
$('#s1').attr('src', 'images/object/click-1.png');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/standard-3.jpg');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section3" class="container-fluid" align="center">
<div class="row row-centered ">
<div id="top-box-1" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-1.jpg" class="std" id="s1" width="300" height="300" />
</a>
</div>
<div id="top-box-2" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-2.jpg" class="std " id="s2" width="300" height="300" />
</a>
</div>
<div id="top-box-3" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-3.jpg" class="std" id="s3" width="300" height="300" />
</a>
</div>
</div>
</div>
To break this down: if (!$(this).is('[src*="click"]')) {
$(this).is allows you to check this against a selector, returning a boolean (true) if it does.
'[src*="click"]' is the selector to determine if the src attribute contains 'click'. Where the * means contains anywhere. There are other combinations like ^= for starts with.
Therefore $(this).is('[src*="click"]') means true if the src has 'click'. But you need to invert this to not contains. That's what the ! is for, meaning if this (the clicked element) has not got 'click' in the src.
Since you're already handling the click event, you'll likely want to perform this logic in that same event. Something structurally like this:
if (/* some condition */) {
window.location.href = someUrl;
}
I guess you'd need to define what that condition is. Would it be based on the current src of the image? Something like this?:
if ($(this).attr('src') === 'images/object/click-1.png') {
window.location.href = someUrl;
}
(You'd also have to define what someUrl is, of course.)

How to show different images using .hover() jQuery

I'm gonna try to explain my issue:
I have span elements, each span element have text, when the user hovers it, it should displays an image next to the element, each image is different, I was trying to use jQuery .hover() function, but when I hover on the text it shows me the whole images.
How can I solve it?.
My HTML.
<table>
<tbody>
<tr>
<td style="width: 20%;" class="text-center">
<span class="displayImage">Azotea </span>
<span class="displayImage">Nivel 8 </span>>
</td>
</tr>
</tbody>
</table>
<div class="col-lg-5 text-left">
<img class="displayed" src="images/azotea-n9.jpg" alt="">
<img class="displayed" src="images/test2.jpg" alt="">
</div>
My Code.
$(".displayImage").hover(function(){
$(".displayed").show();
}, function () {
$(".displayed").hide();
});
Thanks!.
You could associate the span with a particular image via a data attribute and id.
$(".displayImage").hover(function(){
// $(this).attr('data-img') == 'azotea' or 'nivel8'
// so we end up with $('#azotea').show(), for example.
$('#' + $(this).attr('data-img')).show();
}, function () {
$('#' + $(this).attr('data-img')).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td style="width: 20%;" class="text-center">
<span class="displayImage" data-img='azotea'>Azotea </span>
<span class="displayImage" data-img='nivel8'>Nivel 8 </span>
</td>
</tr>
</tbody>
</table>
<div class="col-lg-5 text-left">
<img class="displayed" src="images/azotea-n9.jpg" alt="azotea" id="azotea">
<img class="displayed" src="images/test2.jpg" alt="nivel 8" id="nivel8">
</div>
I try donĀ“t change your html
https://jsfiddle.net/luarmr/hjreda3r/
I add a little css as well for hide the elements from the origin
$(".displayImage").hover(
function(el){
var image = $(this).data('ref');
$(".displayed:nth-child(" + image + ")").show();
}, function () {
$(".displayed").hide();
}
);
I would suggest you to better use css3 instead of jquery, cos jquery slows down productivity of your site on mobile gadgets, so maybe you should look here enter link description here
You need to find common ground between your span & image and without adding anything extra in your markup, that would be the index value of each of them. Obviously, this solution that I recommend below is entirely dependant on the order with which you lay out your HTML.
Take a look at this solution I posted for a similar problem.
So basically, your code should become something like this:
$(".displayed").hide();
$(".displayImage").hover(function(){
$(".displayed").eq($(this).index()).show();
},function(){
$(".displayed").eq($(this).index()).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td style="width: 20%;" class="text-center">
<span class="displayImage">Azotea </span>
<span class="displayImage">Nivel 8 </span>
</td>
</tr>
</tbody>
</table>
<div class="col-lg-5 text-left">
<img class="displayed" src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/JS.jpg" alt="">
<img class="displayed" src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/PIXI.jpg" alt="">
</div>
Hope it helps in some way.
T

Display Select Option Images On Screen

I want to display all select option values on screen. One way I have brainstorm is the following:
<select size="4">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
The problem I have with that is that yes all is displayed, but none of them are clicable. I would want that when one of them is clicked, it redirects the user to another url. I would also want each option to be a banner.
The reason I am doing that is because I have already 10 images known as 10 city, and I want to record the city selection of the user so that I am able to populate the right neighborhood to them.
Update:
Below are the links with their respective images:
<img id="selectNeighbourhood1" src="content/San-Francisco/berkeleyCampanile.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/castro.jpg">
<img id="selectNeighbourhood"src="content/San-Francisco/dogpatch-tasting-room.jpg">
<img id="selectNeighbourhood"src="content/San-Francisco/FD1.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Fishermans-Wharf.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Golden-Gate-Park.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Hayes-Valley.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Marina.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Mid-market.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Mission-district.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Noe-Valley.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Pacific-heights.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Russian-hill.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Soma.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Stanford-university.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Sunset-district.jpg">
<img id="selectNeighbourhood" src="content/San-Francisco/Tenderloin.jpg">
Let this be your html
<select id="select" size="4">
<option value="http://www.google.com">option</option>
<option>option</option>
<option>option</option>
<option>option</option>
</select>
This be your javascript
var select = document.getElementById('select')
select.addEventListener('click', go, false);
function go (e) {
e.preventDefault();
var url = e.target.value;
window.location.href= url;
}
This will allow you to get redirected when clicked on the option
I have something that might work for you. It shows how you can create your own "drop-down", get what the user clicked, and populate a DIV with the appropriate image. I hope that's what you're trying to do.
jsFiddle Demo
The "dropdown menu" is created by DIVs. There's an outer DIV, #top, and a number of child divs, of class .menuitem. The menuitem divs are contained in a wrapper div called #menu, which can slide up/down, giving the appearance of a <select> control.
When you click on a city name, the jQuery code reads the ID of the clicked-on selection, and uses that information to populate a picFrame div. If I was to re-write this, I would do it like this:
revised jsFiddle - instead of inserting the entire img tag, it only updates the src= attribute of the existing img tag
Note that jsFiddle has some issues... it's not a perfect environment. For one, the #head div ("Choose a city") is transparent. It shouldn't be. Also, the city names should be centered -- but jsFiddle does not give preference to an ID (in css, id is supposed to "win" over class)
Anyway, it's a start. Hope it helps.
HTML:
<div id="top">
<div id="head" class="clickable">Choose a City</div>
<div id="menu">
<div class="menuitem clickable" id="m1">
<div class="thepic" id="pic1"><img src="http://placekitten.com/300/50" /></div>
<div class="moveleft">Cupertino</div>
</div>
<div class="menuitem clickable" id="m2">
<div class="thepic" id="pic2"><img src="http://placekitten.com/300/51" /></div>
<div class="moveleft">San Francisco</div>
</div>
<div class="menuitem clickable" id="m3">
<div class="thepic" id="pic3"><img src="http://placekitten.com/300/49" /></div>
<div class="moveleft">Silicon Valley</div>
</div>
</div>
</div>
<div id="picframe"></div>
jQuery:
var themap;
$('#head').click(function(){
$('#menu').animate({
top: 0
},800);
});
$('.menuitem').click(function(){
var loc = this.id;
if (loc=='m1'){
themap = '<img src="http://placekitten.com/g/150/150" />';
}else if (loc=='m2'){
themap = '<img src="http://placekitten.com/149/151" />';
}else{
themap = '<img src="http://placekitten.com/g/151/149" />';
}
$('#menu').animate({
top: '-300px'
},1000);
$('#picframe').html(themap);
});
CSS:
img{opacity:.3;}
.clickable{cursor:pointer;}
#head{height:35px;width:304px;font-size:2em;text-align:center;z-index:2;background:white;}
#menu{position:relative;top:-300px;}
.menuitem{position:relative;width:304px;height:54px;margin:5px 0;}
.thepic{position:absolute;top:0;left:0;}
.moveleft{position:relative;top:10px;left:0;background:transparent;font-size:2em;color:blue;}
#pic1{width:130px;margin:0 auto;}
#pic2{width:200px;margin:0 auto;}
#pic3{width:230px;margin:0 auto;}
#picframe{height:150px;width:150px;border:1px solid grey;}
Reference (re css precedence):
http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

jQuery last child selector

This is not working and I don't know why. I have tried it in the console it works, but when I change my js codes it does not work.
$('#recipe-table td:last-child').width();
How can I get it the correct way?
this is the html
<div id="div-lists">
<div id="div-recipe-table">
<table class="" id="recipe-table" cellspacing="0" cellpadding="0">
<tbody>
<tr class="recipe-list" data-ng-repeat="recipe in recipe_data" ng-click="recipe_click(recipe.CodeListe,recipe.Name)">
<td id="td-img{{recipe.CodeListe}}">
<center>
<span id="img{{recipe.ID}}X">
<a id="{{recipe.ID}}" href="javascript:void(0);">
<img ng-if="recipe.Pictures !==''" fallback-src="images/default.png" ng-src="{{recipe.Pictures}}" class="images" id="img{{recipe.ID}}"/><img ng-if="recipe.Pictures===''" class="images" src="images/default.png" id="img1"/>
</a>
</span>
</center>
</td>
<!-- I want to get The width of this <td> -->
<td class="recipes">
<div id="div-recipe-name">
<strong>{{recipe.Name}}</strong></div>
</td>
<!-- Until here
I already tried using $('.recipes').width(); but it returns 0 -->
</tr>
</tbody>
</table>
</div>
<div id="div-list-loading"></div>
<div id="div-list-noresults">{{ui_translation.UIT[171610]}}</div>
</div>
</div>
Try the following:
$('#recipe-table td:last').width();
From the jQuery Docs
While :last matches only a single element, :last-child can match more
than one: one for each parent.
Since you have already tried $('.recipes').width(); does the following provide you any results:
$('.recipes').each(function (index, elem) {
alert($(this).width());
});
Try below jQuery
You can use .last() method constructs a new jQuery object from the last element in that set.
$('#recipe-table td').last().width();
JSFIDDLE DEMO

Categories