Binding One Click Event to three different links - javascript

I wrote a simple script similar to this example. The problem is the click event is only binding to the first #id in the conditional statement. My thought on why this is occurring is there is nothing in each statement to associate the ID with the class in the click function, but when I tried to add a var, the click did not fire at all. Please tell me where I have gone wrong.
Thanks
$(document).ready(function(){
$('.someclass').bind('click', function() {
if('#id1')
{
window.location = "someURL";
}
else if('#id2')
{
window.location = "someURL2";
}
else if('#id3')
{
window.location = "someURL3";
}
});
});

You can check their id's like this
$(document).ready(function () {
$('.someclass').bind('click', function () {
if(this.id === 'id1') {
window.location = "someURL";
} else if(this.id === 'id2') {
window.location = "someURL2";
} else if(this.id === 'id3') {
window.location = "someURL3";
}
});
});

Consider:
<span data-url="someURL">Link 1</span>
<span data-url="someURL2">Link 2</span>
And then:
$wrapper.on( 'click', 'span', function () {
window.location = $( this ).data( 'url' );
});
where $wrapper contains the DOM element which in turn contains all your "links".
The idea here is to separate the data from the JavaScript code (= the behavior). Your URL's should be in the DOM - you can use data-* attributes to store them (as I've shown above).

Since you already use ids for your elements you should use them seperately to bind the click functions. It's easier and it works :)
$(document).ready(function(){
$('#id1').click(function(){
window.location = "someURL";
});
$('#id2').click(function(){
window.location = "someURL2";
});
$('#id3').click(function(){
window.location = "someURL3";
});
});
If you like the original way better (you shouldn't ;-) ) then try this:
if( $(this).attr("id") == 'id1' )
{
window.location = "someURL";
}

I think you are over thinking things and also not knowing what is out there for you to use. I would leverage the data attribute on your links. I'm going to assume they are not your typical A tag with an HREF because you should not use JavaScript if so.
<div data-url="http://www.someurl1.com">...</div>
<div data-url="http://www.someurl2.com">...</div>
<div data-url="http://www.someurl3.com">...</div>
<script>
$('body').on('click','div[data-url]', function(ev) {
ev.preventDefault();
window.location = $(this).data('url');
}
</script>

If my understanding is correct for your requirement, you have a css class called "someclass" which has hyperlinks into it. You need to set the URL of those hyperlinks dynamically through jQuery, am I correct? If so, then you can try the following code:
<script type="text/javascript" src="../Scripts/jQuery/jquery-1.7.2.js"></script>
<script type="text/ecmascript">
$(document).ready(function () {
$(".someclass > a").live("click", function () {
var currentID = $(this).attr("id");
if (currentID == "id1") {
window.location = "http://google.com";
}
else if (currentID == "id2") {
window.location = "http://stackoverflow.com";
}
else if (currentID == "id3") {
window.location = "http://jquery.com";
}
});
});
</script>
<div>
<div class="someclass">
<a id="id1">id 1</a>
<a id="id2">id 2</a>
<a id="id3">id 3</a>
</div>
</div>

Related

i need to delete target attribute from anchor if its value is null

For the sake of W3c validation i need to remove target attribute from all anchors where target value is null
i had following code inside body
<div>
home emput
home
home empty
home
</div>
Here is my script
$(document).ready(function () {
var target = []
var i = 0;
$("body a").each(function () {
target[i++] = $(this).attr("target");
if($(this).attr("target") == ""){
$(this).removeAttr("target");
}
});
console.log(target);
});
This code is working fine when I view console empty targets are removed. But when I view the source (Ctrl+u), targets are still there,
I just want to delete them.
Try this, its working
$(document).ready(function () {
var target = []
var i = 0;
$("body a").each(function () {
target = $(this).attr("target");
if(target == "")
{
$(this).removeAttr("target");
}
});
//console.log(target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
home emput
home
home empty
home
</div>
As you are using "$", I assume you have jQuery
$("a[target='']").each(function() {
$(this).removeAttr("target");
});
https://jsfiddle.net/6g6t60pa/
try this to remove..
$('a[target=""]').removeAttr('target');
but you cannot achieve this while considering W3 Validation, it grabs page content without executing JS, so the best practice is to hide it using server side script(PHP).

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

If..Then in jQuery to check for open slideToggle()

I am using 'slideToggle' to open a couple divs on a site and want to ensure all of the divs are closed before another is opened. Is there a way to run a if..then to ensure a toggled div isn't open before opening another?
Here is my script;
<script type="text/javascript">
$(function()
{
$("a#toggle").click(function() {
$("#contact").slideToggle(500);
return false;
});
$("a#toggle_about").click(function(){
$("#about").slideToggle(500);
return false;
});
});
</script>
Calling tag;
<li>Contact Me</li>
And called div;
<div id="contact">blah, blah...</div>
And CSS;
#contact{display: none; padding: 7px; font-size: 14px;}
Thanks,
------EDIT------
This seems to work ok, I can control the transition by setting speed to 500 or 0. It just seems like a lot of code for a simple if..then.
Thanks for the suggestions and possible solutions.
<script type="text/javascript">
$(function()
{
$("a#toggle").click(function(){
if ($("#about").is(':hidden')){
$("#contact").slideToggle(500);
return false;
}else{
$("#about").slideToggle(500);
$("#contact").slideToggle(500);
return false;
}
});
$("a#toggle_about").click(function(){
if ($("#contact").is(':hidden')){
$("#about").slideToggle(500);
return false;
}else{
$("#contact").slideToggle(500);
$("#about").slideToggle(500);
return false;
}
});
});
</script>
Fiddle Example
If you add appropriate classes to your html and change the href to target the div it needs to open, you can significantly simplify your code.
<ul>
<li>Contact Me</li>
<li>About Me</li>
</ul>
<div id="contact" class="toggleable">blah, blah...</div>
<div id="about" class="toggleable">blah, blah...</div>
Now you can handle both links with a single event.
$(".toggler").click(function (e) {
e.preventDefault();
var target = $(this).attr("href");
$(".toggleable").not(target).hide();
$(target).slideToggle();
});
the end result is when you click on "Contact Me", about will hide if it is open, and contact will show if it is hidden or hide if it is shown.
http://jsfiddle.net/nYLvw/
You could implement a helper function to collapse any visible elements with a certain class, and then call that every time you're about to toggle a div.
The markup:
<div id="contact" class="toggle-content">blah, blah...</div>
The code:
function hideToggleContent() {
$('.toggle-content:visible').slideUp( 500 );
}
$(function() {
$("#toggle").click( function() {
var isVisible = $("#contact").is(':visible');
hideToggleContent();
if( isVisible ) {
return false;
}
$("#contact").slideDown( 500 );
return false;
});
$("#toggle_about").click( function() {
var isVisible = $("#about").is(':visible');
hideToggleContent();
if( isVisible ) {
return false;
}
$("#about").slideDown( 500 );
return false;
});
});
You might also check out the jQuery UI accordion, it's default behavior accomplishes the same. http://jqueryui.com/accordion/
UPDATE: Added Fiddle Link For Example
There are several ways to solution this problem.
Whenever you are tweening for effect, and you want to only tween if not already tweening, you will want to track the state of your tween.
Typically, you might have a trigger/toggler, and a target. I like to use closures to accomplish the state tracking. I might use something like this:
$(function () {
// closures
var $togglers = $('[selector][, selector]');
var $target = $('[selector]');
$target.tweening = false;
var tweenStop = function () {
$target.tweening = false;
};
var togglerClick = function () {
if (!$target.tweening) {
$target.tweening = true;
$target.slideToggle(500, tweenStop);
}
};
// handle the event
$togglers.click(togglerClick);
});
>> SAMPLE FIDDLE <<

dynamically create element using jquery

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?
Javascript/Jquery
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
<html>
<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>
<body>
<ul class="meny" id="menu">
<li>Utvärdering/Feedback</li>
<li>Kontakt</li>
<li>Öppettider</li>
<li>Om Asperöd</li>
</ul>
<div id="contentl1">
</div>
<div id="contentl2">
</div>
<div id="contentl3">
</div>
<div id="contentl4">
</div>
</body>
</html>
Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:
$("<p />", { text: "Hej" }).appendTo("#contentl1");
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var p = $("<p>");
p.text("Hej");
$("#contentl1").append(p);
}
});
}
For a start the click function can be done like this instead of having to use .find():
$('#menu a').click(function() { }
The .each() loop can be done like:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
I know it doesn't realate to answering your question but it is hard to leave this as a comment:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
You can try this to solve your issue:
function createElement() {
if($(this).attr("id") == "l1"){
$("#contentl1").append('<p>hej</p>');
}
}
$("#menu a").each(function () {
$(this).click(function () {
createElement.apply(this);
});
});
Something like this fiddle?
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});
try this script, it'll do place the text in correct div.
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});
I personally like to use classic JS DOM for tasks so this is how you can first create the DOM object using JQuery. The DOM object returned is the outer element of HTML (p tag) but the inner HTML can be as complex as you want.
var elP = $("<p>Hej</p>")[0]
// Do some other DOM manipulations of p
// eg: elP.someCustomTag='foobar'
$("#content1").append(elP)

jQuery how to get the class or id of last clicked element?

I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...
HTML
Button
JQUERY
$('.button').click(function () {
myFuntion();
});
function myFunction (e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
var lastClickedElement = $.lastClicked;
console.log(lastClickedElement);
}
This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.
I have also tried using this solution but couldn't get it to work with my code.
$('.button').click(function () {
myFuntion();
});
function myFunction(){
var lastID;
lastID = $(this).attr("id");
console.log(lastID);
}
When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.
You can pass clicked element as parameter to your function:
$('.button').click(function () {
myFunction(this);
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
UPDATE added jsfiddle
A couple of ways come to mind:
$(".button").click(myFunction);
Should work with the above myFunction.
$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
var lastID;
lastID = $elem.attr('id');
$.data('lastID', lastID);
}
In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:
var lastClickedElement = $.lastClicked,
lastClickedElementClassNames = lastClickedElement.className;
This does return the full list of all the classes of the element though.
$('.button').click(function () {
myFuntion(this);
});
function myFunction(ele){
var lastID;
lastID = $(ele).attr("id");
console.log(lastID);
}
First Select all possible DOM Elements
var lastSelectedElement = null
$(document).ready(function(){
$("*").live("click",function(){
lastSelectedElement = $(this);
myFunction($(this));
});
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
than you could play with lastSelectedElement by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");

Categories

Resources