Repeating ID uses in javascript - javascript

I have a following set up:
<a href="#" id="A" >My Site</a>
<a href="#" id="A" >Your Site</a>
<a href="#" id="A" >Her site</a>
<a href="#" id="A" >His Site</a>
<a href="#" id="A" >Our Site</a>
And a button:
<a href="#" id="B" >Yay</a>
Then following javascript:
<script>
jQuery("#A").click(function()
{ jQuery("#B").trigger('click');
return false; });
</script>
In this setting, when "A" is clicked, then "B" is clicked as well.
It works well for the very first button ("My Site"). However other buttons are not working as if only the first id was recognized by the javascript and rest are simply ignored.
I mean, I can change the id of other buttons and repeat the javascript, however that seems like a poorly written idea.
What would be the best way of dealing in this situation? (a clean and efficient way).
Also, let say that I do have repeating javascript with different id as example below (for different buttons to trigger different buttons).
<script>
jQuery("#A").click(function()
{ jQuery("#B").trigger('click');
return false; });
jQuery("#C").click(function()
{ jQuery("#D").trigger('click');
return false; });
jQuery("#E").click(function()
{ jQuery("#F").trigger('click');
return false; });
</script>
In this case, is there a way for me to condense the repeating javascripts?
Thanks!

Your HTML is invalid. ID must be unique. JS will take first element with that ID and will ignore rest elements. Use classes for that.
$(document).ready(function() {
$('.A').click(function(e) {
e.preventDefault();
$('#B').trigger('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Site
Your Site
Her site
His Site
Our Site
<hr/>
<button onClick="alert('Clicked B')" id="B">Maybe clicked</button>
If you have to make reference what element must be clicked and your links does not have any link to other page, you can use it's href element:
$(document).ready(function() {
$('.A').click(function() {
$($(this).attr('href')).trigger('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Site
Your Site
Her site
His Site
Our Site
<hr/>
<button onClick="alert('Clicked A')" id="a">Maybe A clicked</button>
<button onClick="alert('Clicked B')" id="b">Maybe B clicked</button>
<button onClick="alert('Clicked C')" id="c">Maybe C clicked</button>

ID of an element must be unique so you can use a class to group similar elements, use a data-* attribute to specify which element's click has to be triggered.
A unique identifier for the element. There must not be multiple
elements in a document that have the same id value.
<a href="#" class="click" data-target="a" >My Site</a>
Your Site
Her site
His Site
Our Site
<a href="#" id="a" >Yay</a>
<a href="#" id="b" >Yay</a>
<a href="#" id="c" >Yay</a>
then
$('.click').click(function(){
$('#' + $(this).data('target')).click();
})

In HTML ID must be unique,You can enclose all anchors inside a block element and do like as follows
<div id="A">
My Site
Your Site
Her site
His Site
Our Site
</div>
Button
<a href="#" id="B" >Yay</a>
Script
<script>
jQuery("#A a").click(function()
{
jQuery("#B").trigger('click');
return false;
});
</script>

The id of an element has to be unique. Thus, I would suggest using a class:
<a href="#" class="A" >My Site</a>
<a href="#" class="A" >Your Site</a>
<a href="#" class="A" >Her site</a>
<a href="#" class="A" >His Site</a>
<a href="#" class="A" >Our Site</a>
Then:
elements = document.getElementsByClassName("A");
for(var i = 0; i < elements.length; i++){
var ele = elements[i];
jQuery(ele).click(function()
{ jQuery("#B").trigger('click');
return false; });
}

Related

How to highlight a link in Javascript

I have a search box on my page. When it is submitted it will jump to the anchor id further down the page based on the id entered into the text box, without refreshing the page (this is key).
Here is my current code.
Javascript:
$(function() {
$('form#unitid_quickfind').submit(function(e) {
var anchor = $("#unitid_input").val();
var position = $("#"+anchor).offset();
window.scrollTo(position.left, position.top);
return false;
});
});
HTML:
<form id="unitid_quickfind">
<input id="unitid_input" type="text" />
<input type="submit" value="Find" />
</form>
<a id="1">Unit 1</a>
<a id="2">Unit 2</a>
<a id="3">Unit 3</a>
Alongside jumping to the anchor when the submit is clicked, I would also like the link highlighted in some way. What is the easiest way to achieve this (preferably adding to the existing Javascript function)?
TIA
You need to select that element and than you can simply apply the style you want.
Here i selected the element by var element = document.getElementById(anchor); by this.
And by using element.style.color = 'green' i changes color of selected element.
$(function() {
$('form#unitid_quickfind').submit(function(e) {
var anchor = $("#unitid_input").val();
var position = $("#"+anchor).offset();
var element = document.getElementById(anchor);
if(element)element.style.color = 'green'
if(position)window.scrollTo(position.left, position.top);
return false;
});
});
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
<form id="unitid_quickfind">
<input id="unitid_input" type="text" />
<input type="submit" value="Find" />
</form>
<a id="1">Unit 1</a>
<a id="2">Unit 2</a>
<a id="3">Unit 3</a>

How can I set or append different base hrefs to different links with JavaScript?

I want to reduce clutter in my web page code by setting multiple base hrefs for hyperlinks. Links with the same base hrefs also have the same CSS classes. Using JavaScript, is there a way to append base hrefs to the relative links? It's very difficult to explain, but here's an example:
<a class="blue" href="sad1.html">Sad 1</a>
<a class="blue" href="sad2.html">Sad 2</a>
<a class="red" href="angry1.html">Angry 1</a>
<a class="red" href="angry2.html">Angry 2</a>
I want to append one base href to all the links with a blue class, and a different base href for all the links with a red class. I'll actually have several more classes in the document, but I can finish the code if someone can provide a working sample. My page has hundreds of links, which I update often, so I need the html as trim as possible. I'm solid on HTML and CSS, but I'm still trying to learn JavaScript. Thanks.
function absolutizeHref(klass, base) {
var nodes = document.querySelectorAll("." + klass + "[href]");
Array.prototype.forEach.call(nodes, function(node) {
var href = node.getAttribute("href");
node.setAttribute("href", base + href);
});
}
document.addEventListener("DOMContentLoaded", function(event) {
absolutizeHref("blue", "http://example.com/blue/");
absolutizeHref("red", "http://example.com/red/");
});
<a class="blue" href="sad1.html">Sad 1</a>
<a class="blue" href="sad2.html">Sad 2</a>
<a class="red" href="angry1.html">Angry 1</a>
<a class="red" href="angry2.html">Angry 2</a>
Just to give you an idea. Something like this:
var links = document.querySelectorAll('a');
for(var i = 0; i < links.length; i++) {
links[i].href = links[i].className + links[i].pathname;
}
<a class="blue" href="sad1.html">Sad 1</a>
<a class="blue" href="sad2.html">Sad 2</a>
<a class="red" href="angry1.html">Angry 1</a>
<a class="red" href="angry2.html">Angry 2</a>
Update after re-reading the question and didn't notice this line at the first time so much..
I want to append one base href to all the links with a blue class, and
a different base href for all the links with a red class.
To stick with the idea it is still quiet simple
var links = {};
links.blue = document.querySelectorAll('a.blue');
links.blue.myPath = '/custom/blue/path';
links.red = document.querySelectorAll('a.red');
links.red.myPath = '/custom/red/path';
for (var key in links) {
for(var i = 0; i < links[key].length; i++) {
links[key][i].href = links[key].myPath + links[key][i].pathname;
}
}
<a class="blue" href="sad1.html">Sad 1</a>
<a class="blue" href="sad2.html">Sad 2</a>
<a class="red" href="angry1.html">Angry 1</a>
<a class="red" href="angry2.html">Angry 2</a>
Another answer here has offered the core-js solution for this.
If you are happy to use jQuery, jQuery will provided the cleanest solution for you.
If you aren't comfortable with jQuery, but are open to using it, a quickstart guide can be found here
Here's an example of solving this in jQuery. The elegance of this solution, is that all you need to do to expand it is add a key value pair to classToPrefixMap:
var classToPrefixMap = {
green: '/path/to/green/',
blue: '/path/to/blue/'
};
for(var key in classToPrefixMap) {
$('.' + key).each(function(index, anchor) {
$(anchor).attr('href', classToPrefixMap[key] + $(anchor).attr('href'));
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="green" href="one.jpg">One</a>
<a class="green" href="two.jpg">Two</a>
<a class="blue" href="three.jpg">Three</a>
<a class="blue" href="four.jpg">Four</a>

Get url before leave page

I have one web site with many random href <a> tags which used to redirect to another page. Is it possible to get which page the browser is trying to redirect when click the links with javascript and set return false and open that page with ajax and show it in a DIV? I am already trying with onclick but i need another easy way if possible.
Any answer appreciated.
<a href="link1" onclick="return false;" />Link A</a>
<a href="link2" onclick="return false;" />Link B</a>
<a href="link3" onclick="return false;" />Link C</a>
<a href="link4" onclick="return false;" />Link D</a>
<div id="links">
<a href="imalink-a" />Link A</a>
<a href="imalink-b" />Link B</a>
</div>
<div id="content"></div>
$('#links').on('click','a',function(e){
e.preventDefault();
var link = $(this).prop('href');
console.log(link);
$( "#content" ).load( link );
});
yes it's possible.
$("a").on('click', function(e){
// avoid the normal function of the <a>
e.preventDefault();
var href = $(this).attr("href");
console.log(href);
var current_location = $(location).attr('href');
console.log(current_location);
//make your ajax request here
$("#google").load(href);
});
$("a").on('click',function(){
event.preventDefault();
url=$(this).attr('href');
});
try this
http://jsfiddle.net/upsidown/J3Nvu/
$(".popup").click(function(e) {
// Prevent browser from following the link
e.preventDefault();
// Get the href attribute value
var url = $(this).attr("href");
// Display it or do what you want here
$("#result").html("Clicked " + url);
});
Link A
Link B
<div id="AjaxDiv"></div>
<script type="text/javascript">
function AjaxLoad(URL)
{
$("#AjaxDiv").load(URL);
}
</script>
**OR**
<div>
<a href="javascript:void(0);" data-href="demo.aspx" class="ajaxload" />Link A</a>
<a href="javascript:void(0);" data-href="2_demo.aspx" class="ajaxload" />Link B</a>
</div>
<div id="AjaxDiv"></div>
<script type="text/javascript">
$(document).ready(function() {
$(".ajaxload").click(function() {
$("#AjaxDiv").load($(this).attr("data-href"));
});
});
</script>

jQuery or Javascript Click function change or add id

Is it possible to change the text "mars-on-newyork" from this links, this is how the links looks like:
<ul>
<li>
<a href="google.com/finder.php?offer=mars-on-newyork">
<img class="the-button-red"/>
</a>
</li>
<li>
<a href="google.com/finder.php?offer=mars-on-newyork">
<img class="the-button-green"/>
</a>
</li>
<li>
<a href="google.com/finder.php?offer=mars-on-newyork">
<img class="the-button-blue"/>
</a>
</li>
</ul>
This code changes my images only:
function changeIt(objName) {
var obj = document.getElementById(objName);
var objId = new Array();
objId[0] = "newyork";
objId[1] = "paris";
objId[2] = "tokyo";
var i;
var tempObj;
for (i = 0; i < objId.length; i++) {
if (objName == objId[i]) {
obj.style.display = "block";
} else {
tempObj = document.getElementById(objId[i]);
tempObj.style.display = "none";
}
}
return;
}
and here is the rest of the html from which the java script changes only the pictures:
<div id="newyork">
<a href="#">
<img src="newyork.jpg"/>
</a>
</div>
<div id="paris" style="display:none">
<img src="paris.jpg" border="0" alt="one"/>
</div>
<div id="tokyo" style="display:none">
<img src="tokyo.jpg" border="0" alt="two" />
</div>
<div style="display:none;">
<a id="one" href="#" onclick="changeIt('newyork');"><img src="newyork.jpg" border="0" alt="one"/></a>
</div>
<div>
<a id="one" href="#" onclick="changeIt('paris');"><img src="paris.jpg" border="0" alt="one"/></a>
</div>
<div>
<a id="two" href="#" onclick="changeIt('tokyo');"><img src="tokyo.jpg" border="0" alt="two"/></a>
</div>
If i click on
<a id="one" href="#" onclick="changeIt('paris');"><img src="paris.jpg" border="0" alt="one"/></a>
i want the text from the links on the ul to change from this:
href="google.com/finder.php?offer=mars-on-newyork
to this:
href="google.com/finder.php?offer=mars-on-paris
and if i click on
<a id="one" href="#" onclick="changeIt('tokyo');"><img src="paris.jpg" border="0" alt="one"/></a>
it changes it to
href="google.com/finder.php?offer=mars-on-tokyo
i want the java script to work like it does, how it changes the images but i also want to take advantage of the click to change the text.
thanks!
I see how it is now, i guess my post wasn't good enough to have piqued you're interest's, i guess i would have to pay a freelancer to help me, thanks anyways guys for your time and help!
Quick answer to "Is it possible to add or change and id from a link?":
$('#link').attr('id', 'yourNewId'); // Change id
Quick solution to "What I also want is not to just change the images but also the id or link"
$('#link').attr('href', 'yourNewUrl'); // Change link
I'm finding it a little hard to understand what you're trying to do, but...
what i also want is not to just change the images but also the id or link from the ul list e.g
OK, to change the link, i.e., the href property of all anchor elements in your ul list, assuming the URL has a fixed format and we can just replace whatever comes after the last "-":
// assume objName = "paris" or whatever
$("ul a").attr("href", function(i, oldVal) {
return oldVal.substr(0, oldVal.lastIndexOf("-") + 1) + objName;
});
If you pass the .attr() method a callback function it will call that function for each element and pass the function the current value - you then return the new value.
The elements in question don't seem to have an id at the moment, so I'm not sure what you mean by wanting to change it.

Efficent function replaceWith for multiple classes

The second "click" function of this script doesn't work, I think it's simply a syntax issue. I'm quite new to this. But I need to find a simple way call the live "click" function once for an array of vars.
The script works, just not the second part.
I'm looking for an efficient way to replaceWith an array of different vars, each matching a classed link, and without creating a new function every time.
Any suggestions would be great!
Thanks in advance
<script type="text/javascript">
$(window).load(function(){
$('a.pow').live("click",function(e) {
webgl = $('<iframe src="http://s..."> </iframe>');
e.preventDefault();
$('#slider-wrapper').replaceWith(webgl);
});
$('a.biff').live("click",function(e) {
video = $('<iframe src="http://s..."> </iframe>');
e.preventDefault();
$('#slider-wrapper').replaceWith(video);
});
});
</script>
html
<div id="slider-wrapper">
<div>
<a class="pow" href="">
</a>
</div>
<div>
<a class="biff" href="">
</a>
</div>
next one could be..
<div>
<a class="batman" href="">
</a>
</div>
</div><-- close slider wrapper -->
You can give all your anchors that will load iframes a common class, move the description of the anchor from class to a custom attribute, and have the event handler to act on the custom attribute instead.
<div id="slider-wrapper">
<div>
<a class="link" href="" data-desc="pow">
</a>
<div>
<div>
<a class="link" href="" data-desc="biff">
</a>
<div>
<div>
<a class="link" href="" data-desc="batman">
</a>
<div>
</div>
And in your script:
<script type="text/javascript">
var desc_url_map = {
"pow" : "http://s...",
"biff" : "http://s...",
"batman" : "http://s..."
};
$(window).load(function () {
$('a.link').live('click', function(evt) {
item = $('<iframe src="' + desc_url_map[this.dataset.desc] + '"></iframe>');
$('#slider-wrapper').replaceWith(item);
evt.preventDefault();
});
});
</script>
Hope there are no bugs :)

Categories

Resources