Here is functioning code on a form that displays a Tweet button -- the button's on a form that displays several images -- when the user clicks one of the images, it becomes the 'selected' image and the Tweet button is supposed to tweet the selected image's name and url:
<a id="tweetBtnId" href="https://twitter.com/share" class="twitter-share-button"
data-text="Check me out on OurWebSite!"
data-url=http://$ourSiteURL
data-via=http://$ourSiteURL data-size="medium" data-count="none">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}
(document,"script", "twitter-wjs");</script>
I have an 'onclick()' handler for the div that displays the image. When the user clicks one of the images, its div's onclick() handler is called and sets that image to be the 'currentlySelectedImage' on the page -- and the onclick() handler then needs to update the Tweet button's 'data-text' attribute with the name of the just-selected image:
// This is part of the code of the 'onclick()' handler for
// the image being selected.
<script>
function handleImageOnClick()
{
var myDynamicTweetText = "name of currently-selected image goes here";
var elem = document.getElementById("tweetBtnId");
alert("The elem is: " + elem); // elem IS NULL !! Dagnabbit.
// this fails because 'elem' is null
elem.setAttribute("data-text", myDynamicTweetText);
// other onclick() code not shown for brevity......
}
</script>
I need to dynamically change the 'data-text' attribute's value in the Tweet button to be the name of the selected image. I added the javascript code above which fails-- the 'elem' obtained from the code here:
var elem = document.getElementById("tweetBtnId");
is null (I think) because of this line in the Twitter tweet button code above:
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
I'm not sure but it looks like the Twitter Tweet button default script overwrites any attempt
to add an 'id' attribute to the Tweet button.
You will see that I added the id="tweetBtnId" to the Tweet button above so I could get access to the Tweet button in my image-selection onclick() handler above, then set the 'data-text' to the name of the just-selected image.
I just doubt that Twitter's design goal for the Tweet button was "we're gonna dumb this sucker WAY down, we'll only let these animals choose ONE data-text value - every Tweet button has to have one hard-coded, "Once-on-the-page" data-text attribute - joke's on them if they try to dynamically change the Tweet button's data-text attribute."
I need to get this to work -- any ideas?
Just put it in a container with a known ID and traverse the document with it:
<div id="someIDiKnow">
<a id="tweetBtnId"...>...</a>
</div>
$("#someIDiKnow a").attr("data-text", "Replacement Text!");
Looks like it's going to be the kludgy hidden form/php variable approach for now -- I'll post back if I find a better work-around.
EDIT: the hidden-form/PHP variable solution has beaten the roadblock put up by Twitter's Tweet button -- I can now successfully, dynamically change the Tweet button text at will, anytime based on the user's client-side input. Per Domenic's astute observation that the question above is too long and has code in it, I'll skip posting the answer here, and I apologize for the length above.
You could use JQuery to update the attribute data-text by adding an onclick action on the image. If you wanted to include the text inside the actual image tag by adding your own attribute to the tag, that could be an easy work around to assembling the tweet text.
For example:
function updateTweetBtn(obj) {
$('#someIDiKnow a').attr('data-text', $(this).attr('tweet'));
}
<img src="/images/myimage.jpg" tweet="This is what I want to tweet" onclick="updateTweetBtn(this);" />
<img src="/images/myimage2.jpg" tweet="This is some other text I want to tweet" onclick="updateTweetBtn(this);" />
using in html
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
Tweet
I managed to change the 'data-text' with javascript
var a = "new text";
document.getElementsByClassName('twitter-share-button')[0].setAttribute("data-text", a);
also worked with document.getElementById('twitter') if you add id='twitter' to <a>
Related
I have an ajax "load more/show less" button on my blog. The default button text is "More Posts" with a down arrow icon.
More Posts button
When the button is clicked, the text changes to "Less Posts", but I can't figure out how to change the icon to an up icon.
Less Posts button
In the code below, I need to change the value of data-icon="7" to data-icon="6".
<a class="et_pb_button et_pb_custom_button_icon el-pagination-button el-button el-show-less" href="https://wbj1.flywheelsites.com/blog/?el_dbe_page" data-icon="7">Less Posts</a>
I tried this jQuery snippet without any luck, but I'm not very skilled in javascript or jQuery so it could be wrong:
document.getElementByClassName("el-show-less").setAttribute("data-icon"), "6");
If you want to change the value of data-icon using pure Javascript you can handle that like this
let element = document.querySelector('.el-show-less');
element.dataset.icon = 7;
Using jQuery you can perform that like this
let element = $('.el-show-less');
element.data('icon', 4);
I currently have made a way so the user can add another text field to the form by pressing on a 'add_another' div, this uses basic JS so when the user presses on the div 'add_another' the div 'author_2' is toggled.
I would like to make it so that when the user presses on the 'add_another' div for a second time it shows 'author_3' div, and when they press 'add_another' again, it then shows 'author_4'. I have put all the CSS and HTML divs in place to support this, I am just trying to adapt my code so it shows one div after another, rather then toggling a single div.
Here is my JS:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('.author_2').toggle();
});
});
</script>
I have tried altering this code, however with no luck.
I haven't added my HTML as it is just 4 divs, 'author_1' 'author_2' ... 3...4
Thankyou for your help
There are two solutions to Your problem.
First one - use static code
It means the max author count is 4 and if user gets to 4, this is it.
If so - You need to store the number of authors already shown.
var authors_shown = 1;
$(document).ready(function() {
$('.add_another').on('click', function(){
authors_shown++;
if (!$('.author_'+authors_shown).is(":visible")) {
$('.author_'+authors_shown).toggle();
}
});
});
But there is also a second - more dynamic option.
What if user wants to input 10 or 20 authors? You don't want to pre render all that html code and hide it. You should clone the div and change its id or if the (HTML) code (for another author) is not too long, you can render it within JS code.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
If it's a form, then change names of input fields to array as author_firstname[]
Also You can store number of added authors in another hidden field (so you know how long to loop the form fields on the server side.
The second option is a bit more complex and longer, but way more dynamic.
You should make another div when clicked on add_another:
something like this:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('<div><input type="text" name="name[]" /></div>').appendTo('.your_container');
});
});
</script>
as you see, input's name has [] which means you should treat with the inputs as an array.
let me know if you got any further questions
good luck.
I am attempting to get the data displayed from a database (it displays it on a dynamic page within a table) and have it as the value for a textfield on a different html page (map.html).
The value will be some sort of postcode/address and I want that to go into my google map page within the destination textfield. So when users check the location of the event they press the 'View on Map' button which will open up the page of the map and the data from the event should already be populated within the textfield.
However nothing appears and instead it remains blank, even when I just put in some dummy text it still doesn't populate. I know that the location value is being fetched as the alert correctly displays the location, but the problem is having it populate in the textfield.
I am using JQuery Mobile/Cordova/JavaScript/JQuery/HTML. The app is a one-page structure, with the exception of map.html which has it's own page.
Any ideas?
Fetching the location value:
$(document).on("click", ".btnMap", function(e){
var location = $(this).data("rowlocation");
viewMap(location);
});
Snippet of Button:
<a data-rowlocation='" + response.rows.item(i).Location + "' href='map.html' onclick='viewMap(location)' data-role='button' rel='external' data-mini='true' class='btnMap'>View on Map</a></td></tr>"
viewMap Function:
function viewMap(location) {
alert(location);
$("#target-dest").val(location);
}
HTML:
<input type="text" name="target-dest" id="target-dest" />
the simplest way of passing the location to a new page - using your existing code would be to append the location as a query string to the href in the link.
<a ...href='map.html?loc='" + response.rows.item(i).Location + "'...
and then on the destination page - use JS to grab the querystring from the URL, split it from the rest of the UURL and pass it to the textbox.
//js on destination page
var locn=location.href;
var locationPortions = locn.split("?loc=");
$('#target-dest").val(locationPortions[1]);
Because the trigger for this is clicking an <a>, the link is causing a loading of the map.html page which negates the updating of the contents of the textbox:
<a ...href='map.html'...
This is taking precedence over the onclick event. You need to either change the link into a button and trigger the function as an onclick event or prevent the link from performing its normal function as other posters have noted with e.preventDefault().
I have a simple html menu, when a menu item is clicked a class of `mg_cats_selected" is added to the anchor tag (which is the menu item).
I would like to copy the text value of the active/selected anchor tag and display it in another div on the page, but I would like to only display it once. When a new item link is clicked, I want to remove the old value from the separate div that I've created it and display the new value of the new selected menu item.
I hope that makes sense.
This is the HTML menu
<div id="mgf_165" class="mg_filter mg_new_filters">
<a rel="163" id="163" class="mgf_id_163 mgf mg_cats_selected left_menu" href="javascript:void(0)">Bathrooms Sinks</a>
<a id="164" rel="164" class="mgf_id_164 mgf left_menu" href="javascript:void(0)">Bowed</a>
</div>
This is the jQuery and the div where I wanna display the text values.
<script type="text/javascript">
jQuery(document).ready(function(){
console.log('test');
jQuery("a.left_menu").click(function(){
var txt = jQuery("a.left_menu").text();
//$(this).attr('rel');
jQuery("#category").append(txt);
});
});
</script>
<div id="category">
</div>
At the moment when I click on, say, "Bowed", this displays in the div
Bathrooms SinksBowed
And if I click again on "Bathroom Sinks", the same thing repeats
Bathrooms SinksBowedBathrooms SinksBowed
How can I deal with that? And did I follow the correct logic here?
You are currently getting the text of all the menu items and then appending it to the div.
You need to get the text of the clicked menu item, and then set the content of the div to the text value of that menu item.
jQuery(this) // the clicked menu item
jQuery('#category').text('VALUE') // set the text content of the tag to VALUE
Working solution on JSFiddle..
See Inside the Event Handling Function to learn more about jQuery event handling.
I have a HTML input field like this
<input type="text" id="Bild"/>
I want to get the value of the input field and store it in a String in my JSP page, something like this
<%
String theString= <input type="text" id="Bild"/>
%>
After that I want to use the string to as a source for my image field, like this
<img src= <%= theString %> >
I have no clue how to do this, and I've been staring at the screen for two hours not getting my head straight. How can I get the value of the input field to use for my image source?
I'm new to JavaScript so if I have to use this, please be very descriptive. Thanks.
Changes a pre-existing image's src when the byt button is clicked.
function bytUtBilden() {
// select <input id="Bild"/>
var bildenFalt = document.getElementById('Bild');
// select <img id="bilden"/>
var bilden = document.getElementById('bilden');
bilden.src = bildenFalt.value;
}
function begynna() {
// select element with id="byt"; when clicked, run bytUtBilden
document.getElementById('byt').addEventListener('click',bytUtBilden,false);
}
// when DOM is loaded, run begynna()
document.addEventListener('DOMContentLoaded',begynna,false);
Edit: Changed it so that it updates when the button is clicked. Also bytUtBilden() can be run from anywhere and it will do the same thing.
var path = $('Bild').val();
$('#imgid').attr('src',path);
Is there a reason to be going through a middle-man? Just grab the value with a direct DOM query as long as you know that the text field does already contain a value:
document.getElementById('Bild').value
In this example I used a button as the action, but you don't need that for the value to be query-able
http://jsfiddle.net/Py2E2/