How to load the content of <h> element using jquery - javascript

I have a tag like:
<h3>Mobile
<img align="middle" alt="Edit" class="attEditCategory" src="/Images/edit.png">
<img align="middle" alt="Delete" class="attDeleteCategory" src="/Images/delete.png">
</h3>
I want to display the text of h3 ie "Mobile" in edit click button (on alert).
$(".attEditCategory").button().on("click", function (event) {});
Please help.

You can use $(this).parent().text() to get the text. Or $(this).closest('h3').text() if there could be more to the hierarchy than shown.
E.g.:
$(".attEditCategory").button().on("click", function (event) {
alert($(this).parent().text());
});
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<h3>Mobile
<img align="middle" alt="Edit" class="attEditCategory" src="/Images/edit.png">
<img align="middle" alt="Delete" class="attDeleteCategory" src="/Images/delete.png">
</h3>
If there could be text inside the buttons (e.g., button or a elements rather than img), $(this).parent().text() would include that text. So in that hypothetical case, it's more difficult (but still quite simple) to get just the text of the element itself and not the text of its children:
alert($(this).parent().contents().map(function() {
return this.nodeType === 3 ? this.nodeValue : ""; // 3 = text node
}).get().join(""));
$(".attEditCategory").button().on("click", function (event) {
alert($(this).parent().contents().map(function() {
return this.nodeType === 3 ? this.nodeValue : ""; // 3 = text node
}).get().join(""));
});
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<h3>Mobile
<a align="middle" alt="Edit" class="attEditCategory">edit</a>
<a align="middle" alt="Delete" class="attDeleteCategory">delete</a>
</h3>

try
$(".attEditCategory").on("click", function (event) {
alert($(this).parent().text())
});
DEMO

SInce the class is a child of the h3 use parent() to target the <h3> and text() to get the text
$(".attEditCategory").button().on("click", function (event) {
alert( $(this).parent().text());
});

$("h3").text();
Official documentation.
To access a specific h3 tag with a class or an id you do something like:
$("#foo").text(); //foo is the id
$(".foo").text(); //foo is the class

Simply:
$('h3').text();
And it returns just: "Mobile". It'll be enough to alert:
alert($('h3').text());

Related

How to add css code in onmouseover="hover('')" [JS]

I can't adjust my text to be center aligned. I tried to put css code in onmouseover="hover('')" but it doesn't work. What is the get around for this?
Middle circle with id="content" that changes the tag on hover
<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>
JS Code that I included in the html tag to change content on hover
<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
JS Code that changes the content of the <p> tag
function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}
everything is working properly but I can't adjust the text to be in the center regard less of the <p> tag length .
The main question is how do i add css code in onmouseover="hover('')"
What i want it to look like
what it looks like
Your code really needed a lot of cleaning up.
You should separate the HTML, CSS and JavaScript. After doing this, debugging is SO much easier and the code is much simpler to follow.
In addition, you had a great deal of duplication in your code. Again, using CSS and JavaScript can remove that redundancy. For example, styling is done with CSS, not HTML. Tags like <b> are deprecated and should no longer be used. By creating CSS styles that incorporate font-weight:bold and applying those styles properly, we can get rid of all the <b> and </b> tags.
// Get all DOM references:
var content = document.getElementById('content');
var cir2 = document.getElementById("circle-2");
var cir3 = document.getElementById("circle-3");
var img1 = document.getElementById("img1");
var img2 = document.getElementById("img2");
// Attach event handlers:
cir2.addEventListener("mouseover", function(){ hover('BPO') });
cir2.addEventListener("mouseout", function(){ hover('Services') });
cir3.addEventListener("mouseover", function(){ hover('Web Development') });
cir3.addEventListener("mouseout", function(){ hover('Services') });
img1.addEventListener("mouseover", function(e){ changeSource(e,'http://plumseattle.com/wp-content/uploads/2016/01/linkedin-logo.jpg') });
img1.addEventListener("mouseout", function(e){ changeSource(e, 'https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png') });
img2.addEventListener("mouseover", function(e){ changeSource(e, 'http://seeklogo.com/images/S/snapchat-logo-2D9C3E7ADA-seeklogo.com.png') });
img2.addEventListener("mouseout", function(e){ changeSource(e, 'https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png') });
function hover(description) {
//console.log(description);
content.textContent = description;
}
function changeSource(evt, source){
evt.target.src = source;
}
content > span { font-weight: bold;}
.scaling { font-weight:bold; }
.img { margin-top:5px;width:100px; }
<div id="circle">
<p id="content">
<span>Services</span>
</p>
</div>
<a href="">
<div class="scaling" id="circle-2">
<img id="img1"
src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png"
class="img">
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img id="img2"
src="https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png"
class="img">
</div>
</a>
Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:
const node = document.getElementById('hover');
node.addEventListener('mouseover', () => {
node.innerText = `Last time mouseover'd at ${new Date()}.`;
});
So, now, you need to update children of #content and src attribute of an image under mouse cursor.
The HTML would look like this:
<p id="content">
Services
</p>
<a href="">
<div class="scaling" id="circle-2">
<img src="/static/img/2.png" />
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img src="/static/img/2.png" />
</div>
</a>
while JS code would look like this:
const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');
circle2.addEventListener('mouseover', () => {
circle2.children[0].src = '/static/img/2b.png';
content.innerText = 'BPO';
});
circle2.addEventListener('mouseout', () => {
circle2.children[0].src = '/static/img/2.png';
content.innerText = 'Services';
});
circle3.addEventListener('mouseover', () => {
circle3.children[0].src = '/static/img/4b.png'
content.innerText = 'Web Development';
});
circle3.addEventListener('mouseout', () => {
circle3.children[0].src = '/static/img/4.png'
content.innerText = 'Services';
});
(check out this fiddle).

Hide or unhide text with button click

I'm new to html and this is our first intro homework assignment for javascript; so naturally I am freaking out! Here is an example of what I'm talking about:
<div class="someclassname"> <a href="image.jpg">
<img src= Image/image.jpg height="80">
</a>
<p>some text to he hidden with the image!</p>
</div>
I have looked everywhere and found similar stuff but I am way to incompetent to translate it into what I am doing
I'm thinking the code should look something like this maybe?
<script>
$(document).ready(function() {
$("Button").click(function() {
$(".someclassname").toggle();
if ($.trim($(this).text()) == 'Hide') {
$(this).text('Show');
} else {
$(this).next('Hide');
}
});
</script>
Am I close? Please help!
You are close enough...
You have a syntax error in your script, missing pair of }) and then place a button in your html
$(document).ready(function() {
$("button").click(function() {
$(".someclassname").toggle();
if ($.trim($(this).text()) == 'Hide') {
$(this).text('Show');
} else {
$(this).next('Hide');
}
});
}); //this is missing
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Hide</button>
<div class="someclassname">
<a href="image.jpg">
<img src="Image/image.jpg" height="80" />
</a>
<p>some text to he hidden with the image!</p>
</div>

JQuery each function to fill array with attributes from HTML images

I'm trying to load an array filled with the src attribute from a series of img tags in my HTML document.
HTML:
<html>
<head>
<title>
JQuery Slider
</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div id = "wrapper">
<h1 class="dark-header">2014 Salt Lake Comic Con FanX</h1>
<div id="background-img">
<img src="img/img01.jpg"/>
</div>
<div>
<img src="img/img02.jpg"/>
</div>
<div>
<img src="img/img03.jpg"/>
</div>
<div>
<img src="img/img04.jpg"/>
</div>
<div>
<img src="img/img05.jpg"/>
</div>
<div>
<img src="img/img06.jpg"/>
</div>
<div>
<img src="img/img07.jpg"/>
</div>
<div>
<img src="img/img08.jpg"/>
</div>
<div>
<img src="img/img09.jpg"/>
</div>
<div>
<img src="img/img10.jpg"/>
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function() {
var source = new Array();
$('img').each(function(attr) {
source.push($('img').attr('src'))
});
console.log(source)
});//end document.ready
The output to the console is an array of 10 elements, but only using the first img attribute. I'm not sure how to get the each function to go through all elements and push them to the array.
Your issue is that $('img').attr('src') will always return the value of the first element in the collection of elements.
As pointed out in comments , you need to look at specific instances within your loop
Another way you can do this is using map() which will create the array for you
var source = $('img').map(function(){
return $(this).attr('src');
}).get();
DEMO
You could try something like this:
var source = [];
$('img').each(function() {
source.push( this.getAttribute('src') );
});
In your each code, you re-select the entire group with $('img') so it is only adding the first one of THAT Selection to your array.
OR
If you aren't using jQuery for anything else, you could do it in straight javascript like this:
document.addEventListener('DOMContentLoaded', getImgAttr);
var source = [];
function getImgAttr() {
var imgs = document.querySelectorAll('img');
[].forEach.call(imgs, function( img ) {
source.push( img.src);
});
}
you need to use 'this' while inside the loop to reference the image, otherwise you are getting the reference to first 'img ' tag.
it should be like this:
$('img').each(function(attr) {
source.push($(this).attr('src'))
});
Your callback function needs to accept a second param...
The first param is the current index of the array and the second param is the object at that index.
You may also utilize the keyword this as suggested above.
Based on my answer your code would look like this:
$('img').each(function(i, img) {
source.push($(img).attr('src'));
// alternatively -> source.push($(this).attr('src'));
});
A second option you may like and puts what you're trying to do onto a single line would be to use the jQuery map function...
var source = $.map($('img'), function(img) { return $(img).attr('src'); });

Open sub link in the same page in html

In html I am having the following tags:
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
On Clicking on 2011-2012 or on 2012-2013 I want to set display property of div tag.
I am using the following Javascript code for this and I am calling the Javascript function in body tag. The output is showing style and display is not an object or property.
<script language="javascript">
function clickHnadler()
{
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert("Span id is "+xsp);
if(xsp.charAt(0)=="M")
{
var oC = document.all("C"& xsp.substring(1,2));
if(oC.STYLE.display == "none")
{
oC.Style.Display = "";
}
else{
oC.Style.Display = "none";
}
}
}
</script>
use jquery:
you can pass in the function the element or the Id:
ex:
<span id=M26>2011-2012</span>
function clickHnadler(element)
{
var id = $(element > span).attr(id);
id[0] = 'c'; //not the nicest way, maybe use a replace or something like that
$(id).show(); //or $(id).css('display','list');
}
You may use clickHandler has following way,
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
You need to bind event spacifically to elements you want to handle click for. for more information please refer following link,
http://docs.oracle.com/cd/E19957-01/816-6409-10/evnt.htm#1009606
Based on what i understand from your question, I come up with this.
<script type="text/javascript" src="jquery1.8.js"></script>
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
2011-2012 details</div>
<br />
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
2012-2013 details
</div>

get source of click in javascript?

I'm designing a webpage which uses very basic javascript.
Here's the code:
html:
<!DOCTYPE html>
<html>
<body>
<img id="apple" onclick="display()" src="images/apple.jpg" width="150" height="150">
<img id="pineapple" onclick="display()" src="images/pineapple.jpg" width="130" height="210">
<br><br>
<div id="description" style="width:300px;height:100px;border-top: 1px solid #000; border-bottom: 4px solid #000; border-left: 2px solid #000;
border-right: 4px solid #000;padding: 5px;"></div>
<br>
<button type="button" onclick="reset()">Reset</button>
<script type="text/javascript" src="obst.js"></script>
</body>
</html>
Here's the javascript:
function display()
{
document.getElementById("description").innerHTML="der Apfel - Apple<br>die Äpfel - Apples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An apple a day keeps the doctor away";
}
function reset()
{
document.getElementById("description").innerHTML="";
}
Clicking on the image of the apple displays text in the description box. Clicking on the image of the pineapple displays some other text in the same place.
Instead of using different functions like apple(), pineapple() to insert text, I thought it would be easier to call a display function whenever something is clicked, and in the display function, if the script could identify the source of the click (that is, which image is clicked), it could insert text accordingly.
How do I go about this identifying the click source?
You can use this.id:
<img id="apple" onclick="display(this.id)" src="images/apple.jpg" width="150" height="150">
<img id="pineapple" onclick="display(this.id)" src="images/pineapple.jpg" width="130" height="210">
then catch the id:
function display(clicked_id)
{
alert(clicked_id);
}
You would pass this to the display() handler, then you can access the properties of the DOM element that received the click. Here is the fiddle: http://jsfiddle.net/dandv/BaNdS/. Essentially,
<img id="apple" onclick="display(this)" ... >
<img id="pineapple" onclick="display(this)" ... >
<script type="text/javascript">
function display(self) {
alert(self.id);
}
</script>
There is a easier way. Use a variable:
function selectFruit(fruit){
if(fruit == 'apple'){
.....
}else if(fruit == 'pinapple'){
.....
}
...
}
I would go in a somewhat different direction:
For each possible "term" have hidden block of text with the desired contents.
In each image tag add the ID of its proper placeholder as a rel attribute.
Have JavaScript running on page load, assigning the click event automatically.
Sample HTML would be:
<img id="apple" src="images/apple.jpg" rel="desc_Apple" width="150" height="150" />
<img id="pineapple" src="images/pineapple.jpg" rel="desc_Pineapple" width="130" height="210" />
<div class="item_placeholder" id="desc_Apple">
der Apfel - Apple<br>die Äpfel - Apples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An apple a day keeps the doctor away
</div>
<div class="item_placeholder" id="desc_Pineapple">
der Apfel - Pineapple<br>die Äpfel - Pineapples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An Pineapple a day keeps the doctor away
</div>
Don't forget CSS to make those hidden:
.item_placeholder { display: none; }
And finally the magic to bind them all:
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
var rel = image.getAttribute("rel");
if (rel && rel.length > 0) {
image.onclick = ItemImageClick;
}
}
};
function ItemImageClick() {
var rel = this.getAttribute("rel");
var placeholder = document.getElementById(rel);
if (placeholder) {
document.getElementById("description").innerHTML = placeholder.innerHTML;
} else {
alert("DEBUG - element not found " + rel);
}
}
Live test case.
Probably the simplest way:
var code, node = document.getElementById('description');
code = {
apple : "Apple",
pineapple: "Pineapple"
};
function display( src ) {
node.innerHTML = node.innerHTML ? "" : code[ src.id ] ;
}​
for ( var i in code ) {
document.getElementById( i ).onclick = function() { display( this ) };
}
Demo on jsFiddle
Simple and easy solution: pass arguments to the display function:
<img id="apple" onclick="display('apple');" …>
<img id="pineapple" onclick="display('pineapple');" …>
Better solution: Use the javascript-only (no JS in HTML markup) traditional or even the advanced event handling model. The listeners (which might be attached to multiple elements) will get passed an event object, from which you can determine which element was clicked. Example:
function clickHandler(eventObj) {
var elem = eventObj.target;
if (elem.nodeName.toLowerCase() == 'img' && elem.id)
display(elem.id);
}

Categories

Resources