change url using jquery for specific css classes - javascript

I am using below code to covert all links in a page - Now i want this conversion to happen only for certain parts of page and not for complete page. I am sure this can be done to specific div tags
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','<url>/pqr.php?'+value);
});
});</script>
Please suggest how can i achive this link conversion for specific div tags.
Example to explain problem statement - Consider following code snippet on which url conversion is required for only class="testclass"
<div class="messageContent">
<article>
<blockquote class="messageText SelectQuoteContainer ugc baseHtml">
<div class="testclass">
Amazon 1
</div>
<i>eps</i><br>
<span style="text-decoration: underline"><b><i>How to avail this offer </i></b></span><br>
<i>Add product into the cart<br>
Login or register<br>
Enter your shipping details<br>
Make the Final Payment.</i><br>
<span style="text-decoration: underline"><span style="font-size: 12px"><b>link</b> </span></span><br>
Amazon 2
<div class="messageTextEndMarker"> </div>
</blockquote>
</article>
</div>
I want to convert only the first url (AMAZON 1) and not the second url (AMAZON 2)
Test snippet on js fiddle - http://jsfiddle.net/bontp6jk/4/

What you want to do is first define the parent class and then for that class select all the link elements.
In jQuery you can use multiple selectors that works as follows:
$("#test") // select div 'test'
$(".myClass") // select class 'myClass'
$(".myClass #test") // select div 'test' in class 'myClass'
$("a") // select all link elements
Therefore, what you need is the following: $(".testclass a") which selects all link elements in the class .testclass. Then you can use jQuery .each() function to do something with the link elements.
$( document ).ready(function() {
$(".testclass a").each(function() {
var value = $(this).attr('href');
alert(value);
});
});
jsFiddle

Try this
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var $this = $(this);
var value = $this.attr('href');
if($this.closest('.testclass').length!==0){
$this.attr('href','http://test.com/url.php?url=' + value + '&uid=test&origin=forum');
$this.attr("target","_blank");
}
});
});

Related

jQuery background changing with id

here thisid stores the id of html element. and I want to change its background colour using the following code
let thisid = 'test';
$("a#" + thisid).css("background-color", "yellow");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="test" href="#">Hello world!</a><br/>
<a id="test2" href="#">Goodbye all</a>
this is not working, but it works if I remove thisid and write it in following way
$("a").css("background-color","yellow");
but it selects all with tag
below is what actually I want to do.
$(document).ready(function() {
// hide all questions
$("h1").hide();
// display first question
$("h1#1").show();
// show selected question
$("a").bind('click',function(){
let thisid = $(this).attr('id');
$("h1").hide();
$("h1#"+thisid).show();
$("a#"+thisid).css("background-color","yellow");
});
});
The argument to the jQuery function ($()) is being treated as a CSS selector. Since you're trying to find an element by ID, you need to start the selector with an octothorpe (#). Starting with a character selects by tag type. Not having your html handy, I'm guessing the actual problem is that the element with ID thisid is not an <a> tag. (You're actually selecting "any a tag with id thisid", but since an ID is unique including the tag type selector is redundant)
You should be able to do something more like this:
let thisid = "two"
$("#"+thisid).css("background-color","yellow");
thisid = "three"
// won't work, element with id `three` is not an 'a' tag
$("a#"+thisid).css("background-color","green");
thisid = "four"
$("div#"+thisid).css("background-color","blue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>

how to recode my jquery/javascript function to be more generic and not require unique identifiers?

I've created a function that works great but it causes me to have a lot more messy html code where I have to initialize it. I would like to see if I can make it more generic where when an object is clicked, the javascript/jquery grabs the href and executes the rest of the function without the need for a unique ID on each object that's clicked.
code that works currently:
<script type="text/javascript">
function linkPrepend(element){
var divelement = document.getElementById(element);
var href=$(divelement).attr('href');
$.get(href,function (hdisplayed) {
$("#content").empty()
.prepend(hdisplayed);
});
}
</script>
html:
<button id="test1" href="page1.html" onclick="linkPrepend('test1')">testButton1</button>
<button id="test2" href="page2.html" onclick="linkPrepend('test2')">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
I'd like to end up having html that looks something like this:
<button href="page1.html" onclick="linkPrepend()">testButton1</button>
<button href="page2.html" onclick="linkPrepend()">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
If there is even a simpler way of doing it please do tell. Maybe there could be a more generic way where the javascript/jquery is using an event handler and listening for a click request? Then I wouldn't even need a onclick html markup?
I would prefer if we could use pure jquery if possible.
I would suggest setting up the click event in JavaScript (during onload or onready) instead of in your markup. Put a common class on the buttons you want to apply this click event to. For example:
<button class="prepend-btn" href="page2.html">testButton1</button>
<script>
$(document).ready(function() {
//Specify click event handler for every element containing the ".prepend-btn" class
$(".prepend-btn").click(function() {
var href = $(this).attr('href'); //this references the element that was clicked
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
</script>
You can pass this instead of an ID.
<button data-href="page2.html" onclick="linkPrepend(this)">testButton1</button>
and then use
function linkPrepend(element) {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
NOTE: You might have noticed that I changed href to data-href. This is because href is an invalid attribute for button so you should be using the HTML 5 data-* attributes.
But if you are using jQuery you should leave aside inline click handlers and use the jQuery handlers
<button data-href="page2.html">testButton1</button>
$(function () {
$('#someparent button').click(function () {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
$('#someparent button') here you can use CSS selectors to find the right buttons, or you can append an extra class to them.
href is not a valid attribute for the button element. You can instead use the data attribute to store custom properties. Your markup could then look like this
<button data-href="page1.html">Test Button 1</button>
<button data-href="page2.html">Test Button 1</button>
<div id="content">
</div>
From there you can use the Has Attribute selector to get all the buttons that have the data-href attribute. jQuery has a function called .load() that will get content and load it into a target for you. So your script will look like
$('button[data-href]').on('click',function(){
$('#content').load($(this).data('href'));
});
looking over the other responses this kinda combines them.
<button data-href="page2.html" class="show">testButton1</button>
<li data-href="page1.html" class="show"></li>
class gives you ability to put this specific javascript function on whatever you choose.
$(".show").click( function(){
var href = $(this).attr("data-href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
This is easily accomplished with some jQuery:
$("button.prepend").click( function(){
var href = $(this).attr("href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
And small HTML modifications (adding prepend class):
<button href="page1.html" class="prepend">testButton1</button>
<button href="page2.html" class="prepend">testButton2</button>
<div id="content"></div>
HTML code
<button href="page1.html" class="showContent">testButton1</button>
<button href="page2.html"class="showContent">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
JS code
<script type="text/javascript">
$('.showContent').click(function(){
var $this = $(this),
$href = $this.attr('href');
$.get($href,function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
});
</script>
Hope it helps.

Dynamically append jQuery slider

I'm trying to dynamically include the div-structure from a jQuery slider into my index page.
$( "body" ).on( "click", ".abc", function() {
var photo = '<li><img src="img/photos/photo-1.png" title="Photo 1"></li>';
// .. other li's
$('#banner-fade ul.bjqs').append(photo);
});
into:
<div class="slider" id="photo_1">
<div id="banner-fade">
<ul class="bjqs">
// here should the list items come.
</ul>
</div>
</div>
The problem is that the javascript is not working, only the first picture is shown. How is this possible?
-> When I paste the li's inside the ul, it will work. But not when I try to append it using jQuery.
Just a demo
$(document).ready(function(){
$(document).on( "click", ".abc", function() {
var photo = '<li><b>test1</b></li>';
$('#banner-fade ul.bjqs').append(photo);
});
});
check this - http://jsfiddle.net/6a6Fx/2/
Look like the same thing I've just answered in other question here.
All you need to do is to wrap your code inside
$(function(), {
// Your code goes here...
});
And make sure your <script></script> tags are both inside <head> container.

how do I add class of div from other page?

I want to remove class of div id from other page anchor link.
firstPage.html
<div class="question show" id="a1">
Sample 1
</div>
<div class="question" id="a2">
Sample 2
</div>
list.html
$(function () {
$("a").click(function () {
$("#a2").addClass('question show');
});
});
</script>
</head>
<body>
Link 1
Link 2
</body>
I want to add class addClass('question show') to that div id which is clicked.
I tried here with Link1 for id=a1
But I'm failed to set class ('question show') help me to correct my code
Please check code here
http://plnkr.co/edit/fzdfjdrRbcWmir5wHcJW?p=preview
I'm taking a different approach. I'll not add the function to list.html. Let the page firstPage.html be called with the value. We will capture the anchor from firstPage.html.
Also, since your all divs have the class 'question'; I'm ignoring that class and targeting only 'show' class.
So, load this function with your firstPage.html:
$(document).ready(function(){
var call = $(location).attr('href').split('#');
var ancr = $.trim(call[1]);
if(ancr === undefined || ancr == ''){
// Anchor not set, do nothing
} else {
if (!$('#'+ancr).hasClass('show')) {
$('#'+ancr).addClass('show');
}
}
});
I also assume you don't have multiple divs with same ID (which generally should not be).
I hope this will do what you need.

filter out which span to update

I have the following div collection in my HTML. It's designed to dynamically replicate according to user interaction.
<div class="bill-item">
<!-- Section for a single item -->
<div class="bill-item-img">
<!-- Section for Item pic -->
</div>
<div class="bill-item-description">
<!-- Section for Item description and pricing -->
<div class="bill-item-name">
<p class="bill-item-name-left">Normal Cofee</p><p class="bill-item-name-right">170.00</p>
<div class="clear"></div>
</div>
<div class="bill-item-price">
<span>170.00 USD</span>
</div>
<div class="bill-item-amount">
<span>2</span>
</div>
</div>
<div class="bill-amount-selection">
<!-- Section where the increment & decrement of item amount goes -->
<a class="amount-increase" href="#"></a>
<a class="amount-decrease" href="#"></a>
</div>
</div>
This is the HTML Rendered image of the elements.
I've written the following script to increase the bill-item-amount span value.
$(".amount-increase").click(function(){
x+=1;
$(".bill-item-amount span").html(x);
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$(".bill-item-amount span").html(x);
}
});
This works great but, it updates the value of both the span elements. what I want is to catch the event of the clicked element (which I do now) and increase the span value of the respective span. How can I filter out which span to update using javascript.?
Something like $(this).parents('.bill-item').find('.bill-item-amount span') should select the right element.
Inside your callback this is assigned to the eventSource.
You should walk the dom tree from the clicked element up until you reach the .bill-item element and the go down to the .bill-item-amount span node
$(".amount-increase").click(function(){
var $span = $(this).parent().parent().find(".bill-item-amount span");
var x = $span.html();
x+=1;
$span.html(x);
});
$(".amount-decrease").click(function(){
var $span = $(this).parent().parent().find(".bill-item-amount span");
var x = $span.html();
if(!x<=0){
x-=1;
$span.html(x);
}
});
Hi dimal update your code:
$(".amount-increase").click(function(){
x+=1;
$(".bill-item-amount").html(x);
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$(".bill-item-amount").html(x);
}
});
dont add span inside the selector [ it changes entire span values]
$(".amount-increase").click(function(){
x+=1;
$("use ur increase span id here").html(x); //
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$("use ur decrease span id here").html(x);
}
});
Inside each function the selector $(".bill-item-amount span") will find all the <span> amounts in the document. You can walk the DOM to find the correct <span> using jQuery or plain JavaScript. You seem to be using jQuery functions so my answer also uses jQuery.
The following code combines the two actions into a single function that increases or decreases the amount based on the class name of the <a> clicked. I also added a return false so that the browser will not follow the href="#" on the anchor.
$('.bill-amount-selection').on('click', 'a', function(){
var change = this.className == 'amount-increase' ? 1 : -1
var $amount = $(this).closest('.bill-item').find('.bill-item-amount span')
var amount = parseInt($amount.html(), 10) + change
$amount.html(amount < 0 ? 0 : amount)
return false
});
The use of .on() means that jQuery v1.7+ is required. I can supply a compatible function with lower jQuery versions if necessary.

Categories

Resources