jquery variable? - javascript

I'm a jQuery novice, I have the following jQuery written to show a div when a specific link on a map is shown:
<div id="locationmap">
<a class="linkhide" id="link1" href="#">Occupier 1</a>
<a class="linkhide" id="link2" href="#">Occupier 2</a>
<a class="linkhide" id="link3" href="#">Occupier 3</a>
</div>
<div id="mapdetail">
<div class="hideme" id="local1" style="display:none;">
<p>Some content one</p>
</div>
<div class="hideme" id="local2" style="display:none;">
<p>Some content two</p>
</div>
<div class="hideme" id="local3" style="display:none;">
<p>Some content three</p>
</div>
</div>
<script type='text/javascript'>//<![CDATA[
$("#link1").mouseover(function() { $("#local1").fadeIn(500); });
$("#link2").mouseover(function() { $("#local2").fadeIn(500); });
$("#link3").mouseover(function() { $("#local3").fadeIn(500); });
$(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });
//]]>
</script>
However, as you can see the .fadeIn(500) is being repeated for each link. How would I make this a variable once and call it for each line? This would save me repeating the same piece of code 30 times or so for each link.
I have a JSfiddle here: http://jsfiddle.net/karlgoldstraw/4NRY7/
Thanks.

function mouseOver(localId) {
return function() { $("#local" + localId).fadeIn(500); }
}
$("#link1").mouseover(mouseOver(1));

you could use a data-attribute to make the connection between the links and the div simpler,,,
<a data-id="2"...
$('a.linkhide').mouseover(function() {
var el = '#local' + $(this).data('id');
$(el).fadeIn(500);
});

Because i don't see it yet i thought i would add my answer here. Though i realize that the above answers are perfectly viable my solution lets the link tell the function what the content to show is called. By adding a javascript function that will inspect the hash value of the link you can use that as a selector to do your fadein's. This would also give the benefit of degrading better as the hash link would still put the user on the correct content in the event javascript is disabled.
JavaScript
var fade = function(){
var contentSelector = this.hash;
$(contentSelector).fadeIn(500);
};
Then to declare the mouseovers:
$("#linkone").mouseover(fade);
$("#linktwo").mouseover(fade);
$("#linkthree").mouseover(fade);
$("#linkfour").mouseover(fade);
Or you could even do it like this:
$(".linkhide").mouseover(fade);
Then on the HTML
<a class="linkhide" id="linkone" href="#content1">Link 1</a>
<a class="linkhide" id="linktwo" href="#content2">Link 2</a>
<a class="linkhide" id="linkthree" href="#content3">Link 3</a>
<a class="linkhide" id="linkfour" href="#content4">Link 4</a>
etc...
JSFiddle - http://jsfiddle.net/4NRY7/11/

This is one way that doesn't involve changing the HTML. As you can probably tell, changing the id of the link could make this much more efficient.
$(".linkhide").mouseover(function() {
var linkDivMap = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4 };
var contentBox =$(this).attr('id').replace('link','');
$("#content" + linkDivMap[contentBox] ).fadeIn(500);
});
$(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });

Replacement for your current script.
This allows you to use a single dynamic function, and a single jQuery.mouseover() call, for all .linkhide elements, to avoid the duplication of code that still results from #MikeThomsen's answer.
$( document ).ready( function () {
$( ".linkhide" ).mouseover( function ( event ) {
var item_id = this.id.match( /([0-9]+)$/ )[1];
$( "#local" + item_id ).fadeIn( 500 );
} );
$( ".linkhide" ).mouseout( function () {
$( ".hideme" ).css( 'display', 'none' );
} );
} );

Related

Substitution of content by js

I have a problem with JS code. Well, the text of the first link changes. The second one stays the same and I would like to change too. How to do it correctly?
HTML:
<h4 class="comments-title">Text1</h4>
<a rel="nofollow" class="comment-reply-link" href="#comment-25416">reply</a>
<a rel="nofollow" class="comment-reply-link" href="#comment-2">reply</a>
JS:
function podmien(klasa, tekst) {
document.querySelector(klasa).innerHTML = tekst;
}
document.addEventListener('DOMContentLoaded', function() {
podmien('.comments-title', 'Com');
podmien('.comment-reply-link', 'Answer');
Document.getElementsByClassName
});
https://jsfiddle.net/tomaszpl/8s43wao5/28/
querySelector will only select the first element. What you need is querySelectorAll to select all elements.
function podmienAll(klasa, tekst) {
document.querySelectorAll(klasa).forEach(v => {
v.innerHTML = tekst;
});
}
document.addEventListener('DOMContentLoaded', function() {
podmienAll('.comments-title', 'Com');
podmienAll('.comment-reply-link', 'Answer');
});
<h4 class="comments-title">Text1</h4>
<a rel="nofollow" class="comment-reply-link" href="#comment-25416">reply</a>
<a rel="nofollow" class="comment-reply-link" href="#comment-2">reply</a>

Need to get the "id" attribute of <a> tag using JS

My JSP has a tag whose id is getting populated dynamically:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
JS:
function GetAdvisorReview(){
var domElement =$(event.target);
console.log(domElement.attr('id'));
alert($(this).attr('id'));
alert(this.id);
alert(event.target.id);
}
Every alert is giving undefined.Please tell me what is wrong with the code.Thanks in advance!!!!
Try using this inside the onclick()
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
And the Js should be:
function GetAdvisorReview(e){
alert(e.id); //Get the Id
}
Where the e is the element that fired the event.
You have HTML markup errors in your loop. I'm assuming those are SO
pasted typos only. Otherwise, fix those as well as my code block displays.
An event listener solution is the approach I would take.
remove the onclick, replace it with a class:
<c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" class="advisors" data-toggle="modal" data-target="#datepay">
<img src="assets/img/services/Icon_Reviews.png" width="50" alt="">
</a>
</c:forEach>
and then listen for that class click event to happen
$(".advisors").click(function() {
alert($(this).attr('id'));
});
demo:
http://jsfiddle.net/pcx6csph/1/
Wilfredo P's is a good approach, but I would suggest to avoid using inline JS by adding a CSS class to all your links and to use addEventListener() (pure JS) or .on() (jQuery) to bind the click event:
JSP:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" class="someClass" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
Pure JS:
var elems = document.getElementsByClassName("someClass");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("click", function() {
alert( elems[0].getAttribute("id") );
});
}
jQuery:
// jQuery
$(document).ready(function() {
$(".someClass", this).on("click", function() {
alert( $(this).attr("id") );
});
});
Demo:
// Pure JS
var elems = document.getElementsByClassName("someClass-js");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("mouseup", function() {
alert( this.getAttribute("id") );
});
}
// jQuery
$(document).ready(function() {
$(".someClass-jquery", this).on("click", function() {
alert( $(this).attr("id") );
});
});
a {
display: block;
}
p {
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>With Pure JS:</p>
<a id="some-link-1" class="someClass-js" href="#">Some Link 1</a>
<a id="some-link-2" class="someClass-js" href="#">Some Link 2</a>
<p>With jQuery:</p>
<a id="some-link-3" class="someClass-jquery" href="#">Some Link 3</a>
<a id="some-link-4" class="someClass-jquery" href="#">Some Link 4</a>
If you want to have the sender element and the event object, you should do this instead:
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this, event)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
Then you can access them like that:
function GetAdvisorReview(sender, e){
alert(sender.id);
alert(e.target.id);
}

Getting data-* attribute for onclick event for an html element

<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
I want to get the data-id and data-option values inside the function goDoSomething(10, 21) I have tried to use this reference: this.data['id'] but it did not work.
How can I do this?
You can achieve this $(identifier).data('id') using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename") if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
Like this:
$(this).data('id');
$(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a element and gets the data-id attribute from it.
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at
https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
you can directly use anchor id or data-action attributes to trigger the event.
Html Code
<a id="option1" data-action="option1" data-id="10" data-option="21" href="javascript:void(0);" title="Click Here">Click Here</a>
jQuery Code:
$('a#option1').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option')) ;
});
OR
$('[data-action="option1"]').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option'));
});
User $() to get jQuery object from your link and data() to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>

Combining sequential jQuery selectors into a single function

BIG EDIT: Updated the code sections, but the question remains the same.
I've got perhaps a unique jQuery issue that I could use some help on.
I've got a function (that works perfectly) that looks like this...
var openslide1 = function() {
$("#slide1").animate({
left: "+=250px",
}, 400, function() {
// Animation complete.
});
$(this).unbind('click', openslide1); \\ to prevent from pushing slide over too many times
};
$("#openslide1").click(openslide1);
My issue is there could be a potentially unlimited number of slides, and therefore "openslides". Each "openslide" selector corresponds with its own unique slide. (e.g. #openslide2 would open #slide2 and unbind #openslide2...so on and so forth).
So how do I combine these into a single variable and function?
And as a side note...I'm also going to want to "re-bind" the #openslide on the click of another event. Currently, I'm able to do them one at a time through this....
$("#closeslide1").click(function() {
$("#slide1").animate({
left: "-=250px",
}, 500, function() {
// Animation complete.
});
$('#openslide1').click(openslide1); \\ rebinds openslide1
});
But once this becomes a combined function, I'm assuming "openslide1" will no longer be the variable for the function. So how would I rebind that click event when #closeslide is clicked. (And obviously I'm going to use the first part of this question to apply to the closeslide variables as well.)
<div class="section">
<a class="edit-btn" id="openslide1" href="#null">edit</a>
<a class="edit-btn" id="openslide2" href="#null">edit</a>
<a class="edit-btn" id="openslide3" href="#null">edit</a>
<a class="edit-btn" id="openslide4" href="#null">edit</a>
</div>
<div class="slide" id="slide1">
<h1>Edit Row</h1>
<p>Prototyping data below, may not reflect link clicked.</p>
Submit <a id="closeslide1" class="btn btn-danger" style="color:#fff" href="#null">Cancel</a>
</div>
<div class="slide" id="slide2">
<h1>Edit Row</h1>
<p>Prototyping data below, may not reflect link clicked.</p>
Submit <a id="closeslide2" class="btn btn-danger" style="color:#fff" href="#null">Cancel</a>
</div>
<div class="slide" id="slide3">
<h1>Edit Row</h1>
<p>Prototyping data below, may not reflect link clicked.</p>
Submit <a id="closeslide3" class="btn btn-danger" style="color:#fff" href="#null">Cancel</a>
</div>
<div class="slide" id="slide4">
<h1>Edit Row</h1>
<p>Prototyping data below, may not reflect link clicked.</p>
Submit <a id="closeslide4" class="btn btn-danger" style="color:#fff" href="#null">Cancel</a>
</div>
PLEASE HELP!
Thanks!
I'll give it a shot, does this help you with portability?
$(".openslide1").click(function() {
openSlide(".slide1", "body", 400, ".openslide1");
});
function openSlide(target, bodyObj, speed, original) {
$(target).animate({
left: "+=250px",
}, speed, function() {
// Animation complete.
});
$(bodyObj).animate({
marginLeft: "+=250px",
}, speed, function() {
// Animation complete.
});
$(original).unbind('click');
}
Change you function to pass a reference to the element (or elements) that you want to manipulate:
var openslide = function(elem) {
var id = elem.attr("id");
$("#" + id.substring(5)).animate({
left: "+=250px",
}, 400, function() {
// Animation complete.
});
$('body').animate({
marginLeft: "+=250px",
}, 400, function() {
// Animation complete.
});
elem.unbind('click', openslide);
};
$(".edit-btn").click(function() {openslide($(this))});
Then you can use a single function for all your elements and you can bind them all at the same time if they have a common class (in this case, I called them .openslide).
Edit: looking at your original question again, I noticed that the element being animated at the start isn't the same element. But if there is an easily defined relationship between it and the element you clicked on (for example, it's a child of the original element, or the next sibling, or something) you can easily come up with the appropriate selector to select it. In the example above, I assumed a sibling relationship with the target element having a class of .targetclass, but change it as suits.
Edit 2: changed it to use the id's on the assumption that id openslide1 will correspond to the element with id slide1.
Construct the links as follows :
<div class="section">
<a class="edit-btn openslide" data-slide="#slide1" href="#null">edit</a>
<a class="edit-btn openslide" data-slide="#slide2" href="#null">edit</a>
<a class="edit-btn openslide" data-slide="#slide3" href="#null">edit</a>
<a class="edit-btn openslide" data-slide="#slide4" href="#null">edit</a>
</div>
And the slides as follows :
<div class="slide" id="slide1">
<h1>Edit Row</h1>
<p>Prototyping data below, may not reflect link clicked.</p>
Submit <a class="closeslide1 btn btn-danger" style="color:#fff" href="#null">Cancel</a>
</div>
It's hard to see exactly what effect is required but the general shape of the handler will be something like this :
$(".openslide, .closeslide").click(function() {
if($("body").filter(":animated").length) { return; } //animation in progress, abort.
var $slide = $($(this).data('slide'));
var state = $slide.data('state') || 'closed';
var sign = (state == 'closed') ? '+' : '-';
$slide.animate({
left: sign + "=250px"
}, 400, function(){
$slide.data('state', (sign == '+') ? 'open' : 'closed');
});
$('body').animate({
marginLeft: sign + "=250px"
}, 400);
return false;
});
untested
As you will see, one function (when it works) will handle both slideopen and slideclose actions.
You will have to adapt the script to achieve precisely what you want.

Jquery hovercard

I'm using http://designwithpc.com/Plugins/Hovercard , but I can't find out how to declare a var on hovercard. Every job-desc has his own ID and it should be call when hovering labels. I hope I explained well.
<li id="577" class="item">
<span>
<h3 class="padding-left"><label class="labeldesc" for="">Text</label></h3>
</span>
<span class="job-descr" id="hiden-577">TextTextTextTextText</span>
</li>
<li id="588" class="item">
<span>
<h3 class="padding-left"><label class="labeldesc" for="">Text2</label></h3>
</span>
<span class="job-descr" id="hiden-588">Text2Text2Text2Text2Text</span>
</li>
Jquery code:
$('.labeldesc').hovercard({
var idhover=$(this).closest('.item').attr('id');
detailsHTML:$("#hiden-" + idhover).html()
});
Give this a shot: http://jsfiddle.net/X2q9z/
$('.labeldesc').hovercard({
onHoverIn: function() {
var txt = $($(this).parents('li')[0]).find('.job-descr').html();
$(this).find('.hover_text').html(txt);
},
detailsHTML: '<div class="hover_text"></div>'
});
First of all your jQuery Code has issue. You cannot use var inside calling hovercard function.
I update it as you wanted. Please take a loot at this: http://jsfiddle.net/cnCmN/
$('.labeldesc').each(function(){
$(this).hovercard({
detailsHTML: $("#hiden-"+$(this).closest('.item').attr('id')).html()
});
});

Categories

Resources